数据类型
使用js时间戳
console.log(Date.now()) //1642471441587
或者转化为时间戳才能使用
Date.parse(“2022/1/18 10:05”) //1642471500000
将时间戳转化成时间格式的方法如下–链接查看
https://mp.weixin.qq.com/s?__biz=MjM5MDA2MTI1MA==&mid=2649121025&idx=2&sn=aff0bf6598f07e6b93f20134b1cfac89&chksm=be5846ac892fcfba7a9c382850cf8783d54d4fe8498843b14957d2bba79fdf39f6cd640c66f5&scene=27
代码
时间戳与正常时间了解了之后就上代码
function get_time_diff(time) {var diff = '';var time_diff = new Date().getTime() - time;// 计算相差年数var years = Math.floor(time_diff / (365 * 24 * 3600 * 1000));if (years > 0) {diff += years + '年';} else {// 计算相差月数var months = Math.floor(time_diff / (30 * 24 * 3600 * 1000));if (months > 0) {diff += months + '月';} else {// 计算相差天数 var days = Math.floor(time_diff / (24 * 3600 * 1000));if (days > 0) {diff += days + '天';} else {// 计算相差小时数 var leave1 = time_diff % (24 * 3600 * 1000);var hours = Math.floor(leave1 / (3600 * 1000));if (hours > 0) {diff += hours + '小时';} else {// 计算相差分钟数 var leave2 = leave1 % (3600 * 1000);var minutes = Math.floor(leave2 / (60 * 1000));if (minutes > 0) {diff += minutes + '分';} else {// 计算相差秒数 var leave3 = leave2 % (60 * 1000);var seconds = Math.round(leave3 / 1000);if (seconds > 0) {diff += seconds + '秒';}}}}}}return diff;
}
其实这个也是抄的 我改了改 改成如果一天前就不显示时分秒这种的了
礼貌贴原文链接
https://juejin.cn/post/6844903704810749965
测试代码
const now = new Date().getTime();// Test cases
const result1 = get_time_diff(now - 2 * 24 * 3600 * 1000);
const result2 = get_time_diff(now - 2 * 3600 * 1000);
const result3 = get_time_diff(now - 2 * 60 * 1000);
const result4 = get_time_diff(now - 2 * 1000);// Assertion
assert.strictEqual(result1, '2天');
assert.strictEqual(result2, '2小时');
assert.strictEqual(result3, '2分');
assert.strictEqual(result4, '2秒');
结果