js:Date格式化

将Date类型格式化为"yyyy/MM/dd HH:mm:ss"

函数代码如下:

复制代码
//Date的prototype 属性可以向对象添加属性和方法。   
Date.prototype.Format = function(fmt){ var o = { "M+": this.getMonth()+1, "d+": this.getDate(), "H+": this.getHours(), "m+": this.getMinutes(), "s+": this.getSeconds(), "S+": this.getMilliseconds() }; //因为date.getFullYear()出来的结果是number类型的,所以为了让结果变成字符串型,下面有两种方法: if(/(y+)/.test(fmt)){ //第一种:利用字符串连接符“+”给date.getFullYear()+"",加一个空字符串便可以将number类型转换成字符串。 fmt=fmt.replace(RegExp.$1,(this.getFullYear()+"").substr(4-RegExp.$1.length)); } for(var k in o){ if (new RegExp("(" + k +")").test(fmt)){ //第二种:使用String()类型进行强制数据类型转换String(date.getFullYear()),这种更容易理解。 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(String(o[k]).length))); } } return fmt; };
复制代码

使用示例:

     var date=new Date().Format("yyyy/MM/dd HH:mm:ss");
     console.log( date);

 

参考博客:http://www.cnblogs.com/zhangpengshou/archive/2012/07/19/2599053.html

posted on   乐之者v  阅读(19631)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

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