/** * 日期时间工具类 */ class DateUtil { /** * 将日期字符串转换为"月日"格式,例如:"5月2日" * @param {string|Date} dateStr - 日期字符串或Date对象,如 "2026-05-02" 或 Date对象 * @returns {string} 返回格式化的日期字符串,如 "5月2日" */ static formatDateToMonthDay(dateStr) { try { const date = typeof dateStr === 'string' ? new Date(dateStr) : dateStr; if (isNaN(date.getTime())) { console.error('Invalid date:', dateStr); return ''; } const month = date.getMonth() + 1; // getMonth()返回0-11,需要加1 const day = date.getDate(); return `${month}月${day}日`; } catch (error) { console.error('Error formatting date:', error); return ''; } } /** * 将日期字符串转换为"年月日"格式,例如:"2026年5月2日" * @param {string|Date} dateStr - 日期字符串或Date对象 * @returns {string} 返回格式化的日期字符串,如 "2026年5月2日" */ static formatDateToYearMonthDay(dateStr) { try { const date = typeof dateStr === 'string' ? new Date(dateStr) : dateStr; if (isNaN(date.getTime())) { console.error('Invalid date:', dateStr); return ''; } const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); return `${year}年${month}月${day}日`; } catch (error) { console.error('Error formatting date:', error); return ''; } } /** * 将日期字符串转换为"YYYY-MM-DD"格式 * @param {string|Date} dateStr - 日期字符串或Date对象 * @returns {string} 返回格式化的日期字符串,如 "2026-05-02" */ static formatDateToYMD(dateStr) { try { const date = typeof dateStr === 'string' ? new Date(dateStr) : dateStr; if (isNaN(date.getTime())) { console.error('Invalid date:', dateStr); return ''; } 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}`; } catch (error) { console.error('Error formatting date:', error); return ''; } } /** * 获取当前日期 * @returns {Date} 返回当前日期的Date对象 */ static getCurrentDate() { return new Date(); } /** * 比较两个日期是否为同一天 * @param {string|Date} date1 - 第一个日期 * @param {string|Date} date2 - 第二个日期 * @returns {boolean} 如果是同一天返回true,否则返回false */ static isSameDay(date1, date2) { try { const d1 = typeof date1 === 'string' ? new Date(date1) : date1; const d2 = typeof date2 === 'string' ? new Date(date2) : date2; if (isNaN(d1.getTime()) || isNaN(d2.getTime())) { return false; } return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate(); } catch (error) { console.error('Error comparing dates:', error); return false; } } } // 导出模块,兼容不同引入方式 if (typeof module !== 'undefined' && module.exports) { module.exports = DateUtil; } else if (typeof window !== 'undefined') { window.DateUtil = DateUtil; }