//友好的时间返回函数(如:10分钟前)time_stamp为UNIX秒数 function friendly_time(time_stamp) { var now_d = new Date(); var now_time = now_d.getTime() / 1000; //获取当前时间的秒数 var f_d = new Date(); f_d.setTime(time_stamp * 1000); var f_time = f_d.toLocaleDateString(); var ct = now_time - time_stamp; var day = 0; if (ct < 0) { f_time = "【预约】" + f_d.toLocaleString(); } else if (ct < 60) { f_time = Math.floor(ct) + '秒前'; } else if (ct < 3600) { f_time = Math.floor(ct / 60) + '分钟前'; } else if (ct < 86400)//一天 { f_time = Math.floor(ct / 3600) + '小时前'; } else if (ct < 604800)//7天 { day = Math.floor(ct / 86400); if (day < 2) f_time = '昨天'; else f_time = day + '天前'; } else { day = Math.floor(ct / 86400); f_time = day + '天前'; } return f_time; } function getd(time1) { var da = new Date(); sda = new Date(time1); var time2 = da.getTime(); var time = 0; if (time1 > time2) { time = time1 - time2; sda = da; } else { time = time2 - time1; } if (time < 1000) return "刚刚"; time = parseInt(time / 1000); if (time > 86400) { var day = parseInt(time / (24 * 60 * 60)); if (day == 1) { return "昨天(" + sda.getHours() + ":" + sda.getMinutes() + ")"; } else if (day < 30) { return day + "天前"; } else if (day < 360) { var moth = parseInt(day / 30); return moth + "个月前"; } else { var year = parseInt(day / 360); return year + "年前"; }; } else if (time > 3600) { var hour = parseInt(time / (60 * 60)); return hour + "小时前"; } else if (time > 60) { var hour = parseInt(time / 60); return hour + "分钟前"; } else { return time + "秒前"; } }
有时win7系统会把时间自动显示为带星期的格式,需要对时间格式处理
var rg = new RegExp("[星期一二三四五六日]","g"); var q = obj_datetine.replace(rg, "").replace("-","https://www.jb51.net/"); //obj_datetine为要处理的时间参数 var d = new Date(Date.parse(q)); return friendly_time(d.getTime() / 1000);