使用效果
console.log(formatDistanceTime('2024-4-10 00:00:00')); // 凌晨0:00
console.log(formatDistanceTime('2024-4-10 06:00:00')); // 上午6:00
console.log(formatDistanceTime('2024-4-10 12:00:00')); // 中午12:00
console.log(formatDistanceTime('2024-4-10 14:00:00')); // 下午14:00
console.log(formatDistanceTime('2024-4-10 18:00:00')); // 晚上18:00
console.log(formatDistanceTime('2024-4-09 12:00:00')); // 昨天 中午12:00
console.log(formatDistanceTime('2024-4-08 12:00:00')); // 周一 中午12:00
console.log(formatDistanceTime('2024-4-06 12:00:00')); // 4月6日 中午12:00
console.log(formatDistanceTime('2023-4-06 12:00:00')); // 2023年4月6日 中午12:00
代码
/**
* 格式化消息距离时间(微信消息时间样式)
* @param {number | string} timestamp 时间戳或时间字符串
*/
function formatDistanceTime(timestamp) {
const now = new Date();
const date = new Date(timestamp);
const hours = date.getHours();
const minutes = date.getMinutes();
let period;
if (hours < 6) {
period = '凌晨';
} else if (hours < 12) {
period = '上午';
} else if (hours < 13) {
period = '中午';
} else if (hours < 18) {
period = '下午';
} else {
period = '晚上';
}
let baseTime = `${period}${hours}:${minutes < 10 ? '0' : ''}${minutes}`;
// 当天
if (
date.getDate() === now.getDate() &&
date.getMonth() === now.getMonth() &&
date.getFullYear() === now.getFullYear()
) {
return baseTime;
}
// 昨天
const yesterday = new Date(now);
yesterday.setDate(now.getDate() - 1);
if (
date.getDate() === yesterday.getDate() &&
date.getMonth() === yesterday.getMonth() &&
date.getFullYear() === yesterday.getFullYear()
) {
return '昨天 ' + baseTime;
}
// 本周内
if (
date.getFullYear() === now.getFullYear() &&
date.getMonth() === now.getMonth() &&
date.getDate() >= now.getDate() - now.getDay() &&
date.getDate() < now.getDate()
) {
const dayOfWeek = date.getDay();
const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
return days[dayOfWeek] + ' ' + baseTime;
}
// 本年内
if (date.getFullYear() === now.getFullYear()) {
const month = date.getMonth() + 1;
const day = date.getDate();
return `${month}月${day}日 ${baseTime}`;
}
// 不是本年
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}年${month}月${day}日 ${baseTime}`;
}