下面是实现此功能的代码,拿走不谢🤫
function humanizeTimeDiff(dateStr) {
const date = new Date(dateStr);
const now = new Date();
const diffSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
if (diffSeconds < 60) {
return '刚刚';
}
const diffMinutes = Math.floor(diffSeconds / 60);
if (diffMinutes < 60) {
return `${diffMinutes}分钟前`;
}
const diffHours = Math.floor(diffMinutes / 60);
if (diffHours < 24) {
return `${diffHours}小时前`;
}
const diffDays = Math.floor(diffHours / 24);
if (diffDays === 1) {
return '昨天';
} else if (diffDays === 2) {
return '前天';
} else if (diffDays < 30) {
return `${diffDays}天前`;
}
const month = date.getMonth() + 1;
const day = date.getDate();
return `${month}月${day}日`;
}
调用方式:
humanizeTimeDiff('2023-02-28 12:12:12');