/** * 格式化日期时间为相对时间(如:刚刚、1分钟前、2小时前等) * @param {string|Date} dateTime - 日期时间(可以是ISO字符串或Date对象) * @returns {string} 格式化后的相对时间 */ function formatRelativeTime(dateTime) { if (!dateTime) { return '刚刚'; } // 确保输入是Date对象 const date = typeof dateTime === 'string' ? new Date(dateTime) : dateTime; if (isNaN(date.getTime())) { return '刚刚'; } // 计算时间差(毫秒) const now = new Date(); const diff = now - date; // 转换为不同的时间单位 const seconds = Math.floor(diff / 1000); const minutes = Math.floor(seconds / 60); const hours = Math.floor(minutes / 60); const days = Math.floor(hours / 24); // 根据时间差返回不同的格式 if (seconds < 60) { return '刚刚'; } else if (minutes < 60) { return `${minutes}分钟前`; } else if (hours < 24) { return `${hours}小时前`; } else if (days < 7) { return `${days}天前`; } else { // 超过7天显示具体日期 const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } } /** * 格式化日期为YYYY-MM-DD HH:MM:SS格式 * @param {string|Date} dateTime - 日期时间(可以是ISO字符串或Date对象) * @returns {string} 格式化后的日期时间 */ function formatDateTime(dateTime) { if (!dateTime) { return ''; } // 确保输入是Date对象 const date = typeof dateTime === 'string' ? new Date(dateTime) : dateTime; if (isNaN(date.getTime())) { return ''; } const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; } /** * 将当前时间转换为北京时区的ISO格式字符串 * @returns {string} 北京时区的ISO格式时间字符串 */ function toBeijingTimeISOString() { const now = new Date(); // 北京时区是UTC+8 const beijingTime = new Date(now.getTime() ); return beijingTime.toISOString(); } module.exports = { formatRelativeTime, formatDateTime, toBeijingTimeISOString };