UNPKG

ql-publish

Version:

31 lines (27 loc) 1.07 kB
/** * 日期格式化函数 * @param {Date} date - 日期对象,默认当前时间 * @param {string} format - 格式化字符串,例如:'yyyy-MM-dd HH:mm:ss' * @returns {string} 格式化后的日期字符串 */ function formatDate(date = new Date(), format = 'yyyy-MM-dd HH:mm:ss') { // 补零函数 const pad = (num) => num.toString().padStart(2, '0'); const year = date.getFullYear(); const month = pad(date.getMonth() + 1); // 月份从0开始 const day = pad(date.getDate()); const hours = pad(date.getHours()); const minutes = pad(date.getMinutes()); const seconds = pad(date.getSeconds()); const milliseconds = date.getMilliseconds().toString().padStart(3, '0'); // 替换格式化字符串中的占位符 return format .replace('yyyy', year) .replace('MM', month) .replace('dd', day) .replace('HH', hours) .replace('mm', minutes) .replace('ss', seconds) .replace('SSS', milliseconds); } module.exports = { formatDate };