js 根据指定日期格式化输出( 刚刚,几分钟前,几小时前,今天,标准日期)
2023-12-13 04:17:04
代码如下:
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 = null
if (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'));
效果:
文章来源:https://blog.csdn.net/gdgztt/article/details/134923448
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!