UNPKG

z-utils-ts

Version:

使用TypeScript编写的工具函数库

74 lines (67 loc) 2.73 kB
/** * 日期格式化函数 * @param date 要格式化的Date对象 * @param format 格式字符串,支持的占位符: * yyyy - 四位年份 * yy - 两位年份 * MM - 两位月份(01-12) * M - 月份(1-12) * dd - 两位日期(01-31) * d - 日期(1-31) * HH - 24小时制两位小时(00-23) * H - 24小时制小时(0-23) * hh - 12小时制两位小时(01-12) * h - 12小时制小时(1-12) * mm - 两位分钟(00-59) * m - 分钟(0-59) * ss - 两位秒数(00-59) * s - 秒数(0-59) * a - 上午/下午(AM/PM) * @returns 格式化后的日期字符串 */ function formatDate(date: Date, format: string): string { // 检查输入是否为有效的Date对象 if (!(date instanceof Date) || isNaN(date.getTime())) { throw new Error("Invalid date object"); } // 获取日期各部分的值 const year = date.getFullYear(); const month = date.getMonth() + 1; // 月份从0开始,需要+1 const day = date.getDate(); const hours24 = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds(); // 处理12小时制 const hours12 = hours24 % 12 || 12; const period = hours24 < 12 ? "AM" : "PM"; // 定义替换规则 const replacements: Record<string, string> = { yyyy: year.toString(), yy: year.toString().slice(-2), MM: month.toString().padStart(2, "0"), M: month.toString(), dd: day.toString().padStart(2, "0"), d: day.toString(), HH: hours24.toString().padStart(2, "0"), H: hours24.toString(), hh: hours12.toString().padStart(2, "0"), h: hours12.toString(), mm: minutes.toString().padStart(2, "0"), m: minutes.toString(), ss: seconds.toString().padStart(2, "0"), s: seconds.toString(), a: period, }; // 替换格式字符串中的占位符 return format.replace(/yyyy|yy|MM|M|dd|d|HH|H|hh|h|mm|m|ss|s|a/g, (match) => { return replacements[match] || match; }); } // 示例用法 const now = new Date(); console.log(formatDate(now, "yyyy-MM-dd")); // 例如: 2025-09-28 console.log(formatDate(now, "yyyy-MM-dd hh:mm:ss")); // 例如: 2025-09-28 console.log(formatDate(now, "MM/d/yyyy")); // 例如: 09/28/2025 console.log(formatDate(now, "hh:mm:ss a")); // 例如: 03:45:22 PM console.log(formatDate(now, "yyyy年MM月dd日 HH:mm:ss")); // 例如: 2025年09月28日 15:45:22 console.log(formatDate(now, "M-d-yy H:m:s")); // 例如: 9-28-25 15:45:22