wuliu_sy/utils/time.js

35 lines
986 B
JavaScript

// 格式化:50分钟前,1小时前.20天前
export const getTimeAgo = (timestamp) => {
const now = Date.now();
const diff = now - new Date(timestamp);
// 计算时间差的毫秒数
const milliseconds = Math.abs(diff);
// 定义时间单位与对应的毫秒数
const timeUnits = [
{ unit: '年', ms: 1000 * 60 * 60 * 24 * 365 },
{ unit: '个月', ms: 1000 * 60 * 60 * 24 * 30 },
{ unit: '周', ms: 1000 * 60 * 60 * 24 * 7 },
{ unit: '天', ms: 1000 * 60 * 60 * 24 },
{ unit: '小时', ms: 1000 * 60 * 60 },
{ unit: '分钟', ms: 1000 * 60 },
];
let str = ''
// 循环遍历时间单位,并计算时间差所对应的单位
for (let i = 0; i < timeUnits.length; i++) {
const { unit, ms } = timeUnits[i];
if (milliseconds >= ms) {
const count = Math.floor(milliseconds / ms);
str = `${count}${unit}`;
break;
}
}
// 如果时间差过小,可以自定义返回结果
return str||'刚刚';
}