前言
俗话说“好记性不如烂笔头”,此文仅用于记录自我知识库
一、dateFormat,时间日期格式化封装函数
为了方便项目需求的各种时间日期格式展示转换,对该功能做的一个封装
二、实现代码
function dateFormat(time, fmt = "yyyy-MM-dd hh:mm:ss") {
if (!time) {
return "";
}
const date = new Date(time);
const o = {
"M+": date.getMonth() + 1,
"d+": date.getDate(),
"h+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds(),
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(date.getFullYear() + "").slice(4 - RegExp.$1.length)
);
}
for (const k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
const str = o[k] + "";
fmt = fmt.replace(
RegExp.$1,
str.padStart(RegExp.$1.length,"0")
);
}
}
return fmt;
}
dateFormat(new Date());
dateFormat(new Date(), "yyyy-MM-dd");
dateFormat("2022-10-21", "yyyy年MM月dd日 hh时mm分ss秒");
dateFormat("2021-06-05 08:29:05", "yy-M-d h:m:s");