Js 日期Date自定义格式输出解决

来源:互联网 发布:java软件开发工作描述 编辑:程序博客网 时间:2024/05/22 17:41

 

1. Javascript中日期的格式化输出比较复杂,  这里采用正则表达式替换相应的格式.

2. new Date中 不是任何日期格式的字符串都可以new成Date对象的, 目前仅发现"yyyy/MM/dd hh:mm:ss"及UTC格式的字符串

 

[javascript] view plaincopyprint?
  1. <script type="text/javascript">  
  2.   
  3. Date.prototype.format = function(format)  
  4. {  
  5.     var o =  
  6.     {  
  7.         "M+" : this.getMonth()+1, //month  
  8.         "d+" : this.getDate(),    //day  
  9.         "h+" : this.getHours(),   //hour  
  10.         "m+" : this.getMinutes(), //minute  
  11.         "s+" : this.getSeconds(), //second  
  12.         "q+" : Math.floor((this.getMonth()+3)/3),  //quarter  
  13.         "S" : this.getMilliseconds() //millisecond  
  14.     }  
  15.     if(/(y+)/.test(format))  
  16.     format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));  
  17.     for(var k in o)  
  18.     if(new RegExp("("+ k +")").test(format))  
  19.     format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));  
  20.     return format;  
  21. }  
  22.   
  23. var ddd = new Date();  
  24. alert(ddd.format('yy-MM-dd hh:mm:ss'));  
  25.   
  26. var a = "2007-12-25 10:00:00" ;  
  27. var d = new Date(a.replace("-","/")) ;  
  28. alert(d.format("yyyy-MM-dd"));  
  29.   
  30. </script>  

原创粉丝点击