/**
* 参数归一化
* 格式化一个日期
* @param {Date} date
*/
function formatDate(date, formatter, isPad = false) {
formatter = _formatNormalize(formatter);
function _pad(value, length) {
if (isPad) {
return (value + "").padStart(length, "0");
} else {
return value.toString();
}
}
const dateInfo = {
year: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate(),
hour: date.getHours(),
minute: date.getMinutes(),
second: date.getSeconds(),
};
dateInfo.YYYY = _pad(dateInfo.year, 4);
dateInfo.MM = _pad(dateInfo.month, 2);
dateInfo.DD = _pad(dateInfo.day, 2);
dateInfo.HH = _pad(dateInfo.hour, 2);
dateInfo.mm = _pad(dateInfo.minute, 2);
dateInfo.ss = _pad(dateInfo.second, 2);
return formatter(dateInfo);
}
function _formatNormalize(formatter) {
if (typeof formatter === "function") {
return formatter;
}
if (typeof formatter !== "string") {
throw new Error("formatter must be a function or a string");
}
if (formatter === "date") {
formatter = "YYYY-MM-DD";
} else if (formatter === "datetime") {
formatter = "YYYY-MM-DD HH:mm:ss";
}
return (dateInfo) => {
const { YYYY, MM, DD, HH, mm, ss } = dateInfo;
return formatter
.replace(/YYYY/g, YYYY)
.replace(/MM/g, MM)
.replace(/DD/g, DD)
.replace(/HH/g, HH)
.replace(/mm/g, mm)
.replace(/ss/g, ss);
};
}
console.log(formatDate(new Date(1218197288000), "YYYY-MM-DD HH:mm:ss", true)); // 2008-08-08 20:08:08
封装一个处理日期格式的函数
最新推荐文章于 2024-08-18 10:54:05 发布