UNPKG

time-format-tools-upgao

Version:

提供了格式化时间的功能

53 lines (45 loc) 1.75 kB
// src/dateFormat.js /** * 格式化日期为指定格式 * @param {string|Date} date - 日期字符串或 Date 对象 * @param {string} format - 格式化字符串,支持 'YYYY-MM-DD', 'MM/DD/YYYY', 'DD-MM-YYYY' 等 * @returns {string} 格式化后的日期字符串 */ function formatDate(date, format) { if (!(date instanceof Date)) { date = new Date(date); // 将输入的日期转化为 Date 对象 } if (isNaN(date)) { throw new Error("Invalid date"); } const map = { 'YYYY': date.getFullYear(), 'MM': String(date.getMonth() + 1).padStart(2, '0'), 'DD': String(date.getDate()).padStart(2, '0'), 'HH': String(date.getHours()).padStart(2, '0'), 'mm': String(date.getMinutes()).padStart(2, '0'), 'ss': String(date.getSeconds()).padStart(2, '0'), 'dddd': getWeekday(date), // 完整星期几(中文) 'ddd': getShortWeekday(date), // 短格式星期几(中文) }; return format.replace(/YYYY|MM|DD|HH|mm|ss|dddd|ddd/g, matched => map[matched] || matched); } /** * 获取日期对应的完整星期几名称(中文) * @param {Date} date - Date 对象 * @returns {string} 完整的星期几名称 */ function getWeekday(date) { const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; return weekdays[date.getDay()]; } /** * 获取日期对应的简短星期几名称(中文) * @param {Date} date - Date 对象 * @returns {string} 简短的星期几名称 */ function getShortWeekday(date) { const weekdays = ['日', '一', '二', '三', '四', '五', '六']; return weekdays[date.getDay()]; } module.exports = { formatDate };