js 根据时间,输出几分钟前,几小时前,几天前,几个月前,几年前。
原文链接:https://blog.csdn.net/qq_42740797/article/details/111277824
代码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) + "分钟前";
} else
result = "刚刚";
return result;
}
console.log(getDateDiff("2020-12-16 12:12:12"));
测试时间:2020年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的在前面补0
if (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) {
// 如果时间格式为2020/07/09 21:43:19.000 需要去掉.000 不然ios和firefox会有问题
return Date.parse(dateStr.replace(/-/gi, "/"));
}
console.log(this.getDateDiff("2020-07-03 10:03:19.000"));
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)