js格式化日期时间

本文介绍了一种在JavaScript中自定义日期格式化的实现方法。通过扩展Date原型,可以轻松地将日期转换为特定格式的字符串。该方法支持年、月、日、时、分、秒及毫秒等多种格式,并提供了周几的中文表示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 // 对Date的扩展,将 Date 转化为指定格式的String
 2 // 月(M)、日(d)、周(E)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
 3 // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 4 // 例子:
 5 // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 6 // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
 7 // 对Date的扩展,将 Date 转化为指定格式的String
 8 // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
 9 // 周(E) 可以用 1-3 个占位符,
10 // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
11 // 例子:
12 // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 20017-04-28 8:18:1.493
13 // (new Date()).Format("yyyy-M-d EE h:m:s.S")      ==> 2017-4-28 周五 8:18:1.503
14 Date.prototype.Format = function(fmt) { //author: meizz
15     var o = {
16         "M+": this.getMonth() + 1,                 //月份
17         "d+": this.getDate(),                    //
18         "h+": this.getHours(),                   //小时
19         "m+": this.getMinutes(),                 //
20         "s+": this.getSeconds(),                 //
21         "q+": Math.floor((this.getMonth() + 3) / 3), //季度
22         "S": this.getMilliseconds()             //毫秒
23     };
24     var week = {
25         "0" : "日",
26         "1" : "一",
27         "2" : "二",
28         "3" : "三",
29         "4" : "四",
30         "5" : "五",
31         "6" : "六"
32     };
33     if (/(y+)/.test(fmt)) {
34         fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
35     }
36     if(/(E+)/.test(fmt)){
37         fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "星期" : "周") : "")+week[this.getDay()+""]);
38     }
39     for (var k in o){
40         if (new RegExp("(" + k + ")").test(fmt)){
41             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
42         };
43     };
44     return fmt;
45 };
46     console.log(new Date().Format("yyyy-M-d EE h:m:s.S") );

 

转载于:https://www.cnblogs.com/iloveyou-sky/p/6778785.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值