方法记录。
百度搜集+自己业务需求整理
/*
获取两个日期的时间差
@param dt1,dt2 yyyy-MM-dd or yyyy-MM-dd hh:mm:ss
返回值单位为:分钟
*/
getIntervalMinutes: function (dt1, dt2) {
if (typeof (dt1) == "string") {
dt1 = new Date(dt1.replace(/-/, '/'));
dt2 = new Date(dt2.replace(/-/, '/'));
}
var res = Math.abs(dt2 - dt1);
if (isNaN(res))
throw Error("invalid dates arguments");
return res / (1000 * 60);
},
//获取当前时间yyyy-MM-dd hh:mm:ss
getNowDateLong: function () {
var nowDate = new Date();
var year = nowDate.getFullYear();
var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) :
nowDate.getMonth() + 1;
var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
.getDate();
var hours = nowDate.getHours() < 10 ? "0" + nowDate.getHours() : nowDate
.getHours();
var minutes = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes() : nowDate
.getMinutes();
var seconds = nowDate.getSeconds() < 10 ? "0" + nowDate.getSeconds() : nowDate
.getSeconds();
var dateStr = year + "-" + month + "-" + day + ' ' + hours + ':' + minutes + ':' + seconds;
//console.log('now date:' + dateStr)
return dateStr
},
//时间过去了多久,刚刚...
getTimeDiff: function (datetimeStr) {
if (undefined === datetimeStr || null == datetimeStr || 'null' == datetimeStr || '' === datetimeStr || datetimeStr == 0) {
return "";
}
var minutes = this.getIntervalMinutes(datetimeStr, this.getNowDateLong())
if (minutes < 2) { // 0-2分钟:刚刚
return '刚刚'
}
if (minutes >= 3 && minutes <= 59) { // 3-59分钟:x分钟前
return Math.floor(minutes) + '分钟前'
}
var hours = minutes / 60
if (hours <= 24) { // 1-24小时:x小时前
return Math.floor(hours) + '小时前'
}
var days = hours / 24
if (days > 1 && days < 4) { // 1天-3天:x天前
return Math.floor(days) + '天前'
}
var year = datetimeStr.substring(0, 4)
var nowyear = new Date().getFullYear()
if (year != nowyear) {
return datetimeStr.substring(0, 10)
} else { // 大于3天未超过1年:具体月-日
return Number(datetimeStr.substring(5, 7)) + '月' + Number(datetimeStr.substring(8, 10)) + '日'
}
}
//Test...
var datetimeStr = '2021-01-03 14:39:50'
//var datetimeStr = '2021-01-04'
console.log(this.getTimeDiff(datetimeStr))