2023-08-05 11:25:45 假如这个就是我们要传的时间字符串
比如今天是2023-08-05(同一天):现在把这个时间字符串传入到 formatDate()这个方法,就会给你返回
11:25
比如今天是2023-08-06(前一天):现在把这个时间字符串传入到 formatDate()这个方法,就会给你返回
昨日11:25
比如今天是2023-08-07或者2023-08-10或2023-12-30:现在把这个时间字符串传入到 formatDate()这个方法,就会给你返回
08-05 11:25
比如今天是2024-08-07(24年任何一个日期):现在把这个时间字符串传入到 formatDate()这个方法,就会给你返回
2023-08-05 11:25
适用于聊天上边的时间显示
//时间处理
formatDate(dateTime) {
const now = new Date();
const date = new Date(dateTime);
if (date.toDateString() === now.toDateString()) {
// 今天的日期,返回时间 HH:mm
return this.formatTime(date);
} else if (date.toDateString() === new Date(now.getTime() - 86400000).toDateString()) {
// 昨天的日期,返回 "昨日 HH:mm"
return "昨日 " + this.formatTime(date);
} else if (date.getFullYear() === now.getFullYear()) {
// 今年的日期,返回 MM-dd HH:mm
return this.formatDateOnly(date) + " " + this.formatTime(date);
} else {
// 去年及以前的日期,返回 yyyy-MM-dd HH:mm
return this.formatFullDate(date) + " " + this.formatTime(date);
}
},
formatTime(date) {
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
},
formatDateOnly(date) {
return date.toLocaleDateString([], { month: '2-digit', day: '2-digit' });
},
formatFullDate(date) {
return date.toISOString().slice(0, 10);
}