JS时间对象new Date的基本用法与日期时间格式化技巧
最编程
2024-08-03 20:22:39
...
function dateFormat(date, fmt = "yyyy年MM月dd日") {
if (date == null) return null;
if (typeof date === "string") {
date = date.slice(0, 19).replace("T", " ").replace(/-/g, "/");
date = new Date(date);
} else if (typeof date === "number") {
date = new Date(date);
}
var o = {
"M+": date.getMonth() + 1,
"[Dd]+": date.getDate(),
"h+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds(),
"q+": Math.floor((date.getMonth() + 3) / 3),
S: date.getMilliseconds(),
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(
RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length)
);
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1
? o[k]
: ("00" + o[k]).substr(("" + o[k]).length)
);
}
return fmt;
}
console.log(dateFormat("2022-11-02T02:51:56.373Z", "yyyy年MM月DD日 hh:mm:ss")); //2022年11月02日 02:51:56
console.log(dateFormat(new Date())); //2022年11月02日
console.log(dateFormat(1667358481422)); //2022年11月02日
上一篇: JavaScript日期格式转换指南