1 const DataFormat = (fmt, date) => {
2 let data = new Date(date);
3 if (isNaN(data)) {
4 data = new Date();
5 }
6 (() => {
7 const o = {
8 'y+': data.getFullYear(),
9 'M+': data.getMonth() + 1, // 月份
10 'd+': data.getDate(), // 日
11 'H+': data.getHours(), // 小时
12 'm+': data.getMinutes(), // 分
13 's+': data.getSeconds(), // 秒
14 'q+': Math.floor((data.getMonth() + 3) / 3), // 季度
15 S: data.getMilliseconds() // 毫秒
16 };
17 for (const k in o) {
18 const regex = new RegExp(k); // 使用new RegExp创建正则表达式
19 if (regex.test(fmt)) { // 检查fmt中是否存在对应的日期格式
20 fmt = fmt.replace(
21 regex,
22 fmt.match(regex)[0].length === 1
23 ? o[k]
24 : ('00' + o[k]).slice(-fmt.match(regex)[0].length)
25
26 );
27 }
28 }
29 })();
30 return fmt;
31 };
1 console.log(DataFormat('yy-MM-ddTHH:mm:ss', new Date('07 09 2323')));
2 // 23-07-09T00:00:00
3
4 console.log(DataFormat('yyyy/MM/dd HH:mm:ss'));
5 // 2023/12/07 10:11:09
6
7 console.log(DataFormat('yyyy/MM/dd HH:mm:ss', 'abc'));
8 // 2023/12/07 10:11:09
9
10 console.log(DataFormat('yyyy-M-d HH:mm:s', 1701915069821));
11 // 2023-12-7 10:11:9
12
13 console.log(DataFormat());
14 // 2023-12-07