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'); } //计算时间间隔 static calculateTimeDifference(startTimestamp: number, endTimestamp: number): string { const diff = Math.abs(endTimestamp - startTimestamp); // 计算小时、分钟和秒数 const hours = Math.floor(diff / (1000 * 60 * 60)); const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((diff % (1000 * 60)) / 1000); // 根据间隔的大小返回不同的格式 if (diff < 60000) { return `${seconds}秒`; } else if (diff < 3600000) { return `${minutes}分${seconds}秒`; } else { return `${hours}小时${minutes}分${seconds}秒`; } } }