一个格式化时间戳的函数

复制代码
 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
复制代码

 

posted @   人恒过  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示