代码如下:
function getDateStr(stringTime) {let str = stringTime;//将字符串转换成时间格式let timePublish = new Date(str);let timeNow = new Date();let minute = 1000 * 60;let hour = minute * 60;let day = hour * 24;let month = day * 30;let year = month * 12;let diffValue = timeNow - timePublish;//let diffMonth = diffValue / month;//let diffWeek = diffValue / (7 * day);let diffDay = diffValue / day;let diffHour = diffValue / hour;let diffMinute = diffValue / minute;//let diffYear = diffValue / year;let result = nullif (diffValue < 0) {result = "刚刚";} else if (diffHour > 1 && diffHour < 3) {result = parseInt(diffHour) + "小时前";} else if (diffMinute > 1 && diffMinute < 60 ) {result = parseInt(diffMinute) + "分钟前";} else if (diffHour >= 3 && diffDay < 1) {result = "今天";} else {result = getJsDateTime(stringTime);}return result;}
依赖方法getJsDateTime:
function getJsDateTime(dateStr) {if ((dateStr == null) ||(dateStr == "")){return "";} else {var date = new Date(dateStr);return dateFtt("yyyy-MM-dd hh:mm:ss",date);}
}
依赖方法dateFtt:
function dateFtt(fmt,date) {var o = {"M+" : date.getMonth()+1, //月份"d+" : date.getDate(), //日"h+" : date.getHours(), //小时"m+" : date.getMinutes(), //分"s+" : date.getSeconds(), //秒"q+" : Math.floor((date.getMonth()+3)/3), //季度"S" : date.getMilliseconds() //毫秒};if(/(y+)/.test(fmt))fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));for(var k in o)if(new RegExp("("+ k +")").test(fmt))fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));return fmt;
}
测试:
console.log("现在===", getJsDateTime(new Date()));console.log("2023-12-11 11:40:00========", getDateStr('2023-12-11 11:40:00'));console.log("2023-12-11 11:00:00========", getDateStr('2023-12-11 11:00:00'));console.log("2023-12-11 10:00:00========", getDateStr('2023-12-11 10:00:00'));console.log("2023-12-11 05:00:00========", getDateStr('2023-12-11 05:00:00'));
效果: