格式化x年前佛致、x月前讶凉、x周前、x天前瘫辩、x小時(shí)前伏嗜、x分鐘前、剛剛
const formatDate = (date: Date): string => {
// 當(dāng)前時(shí)間
const nowDate = new Date();
// 計(jì)算目標(biāo)日期和當(dāng)前日期之間的天數(shù)差異
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八酒,則表示目標(biāo)日期是今天
else if (inactiveDays === 0) {
const now = new Date();
const runTime = Math.floor((now.getTime() - date.getTime()) / 1000);
// 計(jì)算時(shí)間差異
const runMonthTime = runTime % (86400 * 365);
const runDayTime = runMonthTime % (86400 * 30);
const runHourTime = runDayTime % 86400;
const runMinuteTime = runHourTime % 3600;
const runSecondTime = runMinuteTime % 60;
// 提取小時(shí)、分鐘刃唐、秒鐘
const hour = Math.floor(runHourTime / 3600);
const minute = Math.floor(runMinuteTime / 60);
const second = runSecondTime;
// 如果時(shí)間差異大于0羞迷,則返回 X 小時(shí)前
if (hour > 0) {
return `${hour}小時(shí)前`;
}
// 如果時(shí)間差異等于0且分鐘差異大于0,則返回 X 分鐘前
else if (hour === 0 && minute > 0) {
return `${minute}分鐘前`;
}
// 如果時(shí)間差異等于0且分鐘差異等于0画饥,則表示目標(biāo)日期是現(xiàn)在
else if (hour === 0 && minute === 0) {
return "剛剛";
}
}
return "";
};