代码1:
// 时间戳转多少分钟之前function getDateDiff(dateTimeStamp) {// 时间字符串转时间戳var timestamp = new Date(dateTimeStamp).getTime();var minute = 1000 * 60;var hour = minute * 60;var day = hour * 24;var halfamonth = day * 15;var month = day * 30;var year = day * 365;var now = new Date().getTime();var diffValue = now - timestamp;var result;if (diffValue < 0) {return;}var yearC = diffValue / year;var monthC = diffValue / month;var weekC = diffValue / (7 * day);var dayC = diffValue / day;var hourC = diffValue / hour;var minC = diffValue / minute;if (yearC >= 1) {result = "" + parseInt(yearC) + "年前";} else if (monthC >= 1) {result = "" + parseInt(monthC) + "月前";} else if (weekC >= 1) {result = "" + parseInt(weekC) + "周前";} else if (dayC >= 1) {result = "" + parseInt(dayC) + "天前";} else if (hourC >= 1) {result = "" + parseInt(hourC) + "小时前";} else if (minC >= 1) {result = "" + parseInt(minC) + "分钟前";} elseresult = "刚刚";return result;}console.log(getDateDiff("-12-16 12:12:12"));
测试时间:12月16日14:30:21,输出结果:2小时前。
代码2:
function getDateDiff(dateStr) {var publishTime = getDateTimeStamp(dateStr) / 1000,d_seconds,d_minutes,d_hours,d_days,timeNow = parseInt(new Date().getTime() / 1000),d,date = new Date(publishTime * 1000),Y = date.getFullYear(),M = date.getMonth() + 1,D = date.getDate(),H = date.getHours(),m = date.getMinutes(),s = date.getSeconds();//小于10的在前面补0if (M < 10) {M = '0' + M;}if (D < 10) {D = '0' + D;}if (H < 10) {H = '0' + H;}if (m < 10) {m = '0' + m;}if (s < 10) {s = '0' + s;}d = timeNow - publishTime;d_days = parseInt(d / 86400);d_hours = parseInt(d / 3600);d_minutes = parseInt(d / 60);d_seconds = parseInt(d);if (d_days > 0 && d_days < 3) {return d_days + '天前';} else if (d_days <= 0 && d_hours > 0) {return d_hours + '小时前';} else if (d_hours <= 0 && d_minutes > 0) {return d_minutes + '分钟前';} else if (d_seconds < 60) {if (d_seconds <= 0) {return '刚刚';} else {return d_seconds + '秒前';}} else if (d_days >= 3 && d_days < 30) {return M + '-' + D + ' ' + H + ':' + m;} else if (d_days >= 30) {return Y + '-' + M + '-' + D + ' ' + H + ':' + m;}}function getDateTimeStamp(dateStr) {// 如果时间格式为/07/09 21:43:19.000 需要去掉.000 不然ios和firefox会有问题return Date.parse(dateStr.replace(/-/gi, "/"));}console.log(this.getDateDiff("-07-03 10:03:19.000"));
如果觉得《js 根据时间 输出几分钟前 几小时前 几天前 几个月前 几年前。》对你有帮助,请点赞、收藏,并留下你的观点哦!