新建timeUtil.js
参数说明:
timestamp 秒级/毫秒级时间戳
isMilliseconds 是否是毫秒级时间戳
// timeUtil.js
export function formatTime(timestamp, isMilliseconds = false) {
let ts = parseInt(isMilliseconds ? timestamp / 1000 : timestamp, 10);
const now = Math.floor(Date.now() / 1000);
const diff = now - ts;
if (diff < 60) {
return '刚刚';
} else if (diff < 3600) {
return `${Math.floor(diff / 60)}分钟前`;
} else if (diff < 86400) {
return `${Math.floor(diff / 3600)}小时前`;
} else if (diff < 259200) { // 3天内
return `${Math.floor(diff / 86400)}天前`;
} else {
const date = new Date(ts * 1000);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}`;
}
}
使用效果
formatTime(156456456456) // 刚刚
formatTime(156456499956) // 1分钟前
formatTime(156443499956) // 1小时前
formatTime(159443499956) // 1天前
formatTime(159433499956) // 2021-05-17 21:20
感谢你的阅读,如对你有帮助请收藏+关注!
只分享干货实战和精品,从不啰嗦!!!
如某处不对请留言评论,欢迎指正~
博主可收徒、常玩QQ飞车,可一起来玩玩鸭~