格式化x年前、x月前、x周前、x天前、x小时前、x分钟前、刚刚
const formatDate = (date: Date): string => {
// 当前时间
const nowDate = new Date();
// 计算目标日期和当前日期之间的天数差异
const inactiveDays = Math.floor((Date.UTC(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate()) - Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())) / (1000 * 3600 * 24));
// 如果日期差异大于等于30天且小于365天,则返回 X 月前
if (inactiveDays >= 30 && inactiveDays < 365) {
return `${Math.floor(inactiveDays / 30)}月前`;
}
// 如果日期差异大于等于7天且小于30天,则返回 X 周前
if (inactiveDays >= 7 && inactiveDays < 30) {
return `${Math.floor(inactiveDays / 7)}周前`;
}
// 如果日期差异小于30天且大于等于1天,则返回 X 天前
else if (inactiveDays < 7 && inactiveDays >= 1) {
return `${inactiveDays}天前`;
}
//如果日期差异大于365天,则返回 X 年前
else if (inactiveDays > 365) {
return `${Math.floor(inactiveDays / 365)}年前`;
}
// 如果日期差异为0,则表示目标日期是今天
else if (inactiveDays === 0) {
const now = new Date();
const runTime = Math.floor((now.getTime() - date.getTime()) / 1000);
// 计算时间差异
const runMonthTime = runTime % (86400 * 365);
const runDayTime = runMonthTime % (86400 * 30);
const runHourTime = runDayTime % 86400;
const runMinuteTime = runHourTime % 3600;
const runSecondTime = runMinuteTime % 60;
// 提取小时、分钟、秒钟
const hour = Math.floor(runHourTime / 3600);
const minute = Math.floor(runMinuteTime / 60);
const second = runSecondTime;
// 如果时间差异大于0,则返回 X 小时前
if (hour > 0) {
return `${hour}小时前`;
}
// 如果时间差异等于0且分钟差异大于0,则返回 X 分钟前
else if (hour === 0 && minute > 0) {
return `${minute}分钟前`;
}
// 如果时间差异等于0且分钟差异等于0,则表示目标日期是现在
else if (hour === 0 && minute === 0) {
return "刚刚";
}
}
return "";
};