export class TimeFormatter { static formatTimestamp(timestamp: number): string { const currentDate = new Date(); const inputDate = new Date(timestamp); // 判断是否是今天 if ( inputDate.getDate() === currentDate.getDate() && inputDate.getMonth() === currentDate.getMonth() && inputDate.getFullYear() === currentDate.getFullYear() ) { return `今天 ${TimeFormatter.formatTime(inputDate)}`; } // 判断是否是昨天 const yesterday = new Date(); yesterday.setDate(currentDate.getDate() - 1); if ( inputDate.getDate() === yesterday.getDate() && inputDate.getMonth() === yesterday.getMonth() && inputDate.getFullYear() === yesterday.getFullYear() ) { return `昨天 ${TimeFormatter.formatTime(inputDate)}`; } // 判断是否是明天 const tomorrow = new Date(); tomorrow.setDate(currentDate.getDate() + 1); if ( inputDate.getDate() === tomorrow.getDate() && inputDate.getMonth() === tomorrow.getMonth() && inputDate.getFullYear() === tomorrow.getFullYear() ) { return `明天 ${TimeFormatter.formatTime(inputDate)}`; } // 返回 YYYY-MM-DD HH:mm return `${inputDate.getFullYear()}-${TimeFormatter.formatNumber(inputDate.getMonth() + 1)}-${TimeFormatter.formatNumber( inputDate.getDate() )} ${TimeFormatter.formatTime(inputDate)}`; } static formatTime(date: Date): string { return `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}`; } static formatNumber(num: number): string { return num.toString().padStart(2, '0'); } }