import { t } from './i18n' export function caculateTimeago(dateTimeStamp: number): string { /* dateTimeStamp 格式为时间戳 1747099388981 1. 刚刚,1分钟内,如 刚刚 2. 今天的,就显示时间,如 17:45 ; 3. 昨天的,参考微信,显示:昨天 17:34 (注意汉字和时间有空格); 4. 今年的,前天及以前,显示:3月6日 17:34 ; 5. 去年的,如 2025年3月6日 17:34 */ const minute = 1000 * 60; const now = new Date().getTime(); const diffValue = now - dateTimeStamp; let result = ''; if (diffValue < 0) { return t('nowText'); } const minC = Math.floor(diffValue / minute); // 刚刚:1分钟内 if (minC === 0) { result = t('nowText'); // 刚刚 } // 今天:当天 else if (isToday(dateTimeStamp)) { const timeStr = formatTime(dateTimeStamp); result = timeStr; // 如 "17:45" } // 昨天:前一天 else if (isYesterday(dateTimeStamp)) { const timeStr = formatTime(dateTimeStamp); result = `昨天 ${timeStr}`; // 如 "昨天 17:45" } // 更早:显示具体日期时间 else { result = formatDateWithYear(dateTimeStamp); // 如 "2025年3月6日 17:34" } return result; } function isToday(timestamp: number): boolean { const today = new Date(); const date = new Date(timestamp); return ( date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate() ); } function isYesterday(timestamp: number): boolean { const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); const date = new Date(timestamp); return ( date.getFullYear() === yesterday.getFullYear() && date.getMonth() === yesterday.getMonth() && date.getDate() === yesterday.getDate() ); } function formatTime(timestamp: number): string { const date = new Date(timestamp); const hours = date.getHours().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0'); return `${hours}:${minutes}`; } function formatDateWithYear(timestamp: number): string { const date = new Date(timestamp); const now = new Date(); const isThisYear = date.getFullYear() === now.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); const hours = date.getHours().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0'); if (isThisYear) { return `${month}月${day}日 ${hours}:${minutes}`; // 如 "3月6日 17:34" } else { const year = date.getFullYear(); return `${year}年${month}月${day}日 ${hours}:${minutes}`; // 如 "2025年3月6日 17:34" } } export const formatDateRange = (type) => { const date = new Date() let year = date.getFullYear() let month: string | number = date.getMonth() + 1 let day: string | number = date.getDate() if (type === 'start') { year = year - 100 } else if (type === 'end') { year = year } month = month > 9 ? month : '0' + month day = day > 9 ? day : '0' + day return `${year}-${month}-${day}` }