js 格式化时间

 1 /**     
 2  *转换long值为日期字符串     
 3  * @param l long值     
 4  * @param pattern 格式字符串,例如:yyyy-MM-dd hh:mm:ss     
 5  * @return 符合要求的日期字符串     
 6  */      
 7 invalid Date 是 new Date(l)中的l是字符串发生的异常
 8  function getFormatDateByLong(l) {
 9      if(l==''){
10          return "";
11      }else{
12         l=parseInt(l);
13      return getFormatDate(new Date(l), "yyyy-MM-dd hh:mm:ss");
14      }
15  }    
16  /**     
17  *转换日期对象为日期字符串     
18  * @param l long值     
19  * @param pattern 格式字符串,例如:yyyy-MM-dd hh:mm:ss     
20  * @return 符合要求的日期字符串     
21  */      
22  function getFormatDate(date, pattern) {    
23      if (date == undefined) {    
24          date = new Date();    
25      }    
26      if (pattern == undefined) {    
27          pattern = "yyyy-MM-dd hh:mm:ss";    
28      }    
29      return date.format(pattern);    
30  }  
31 //格式化json时间类型
32 function toDate(objDate) {
33     var date = new Date();
34     date.setTime(objDate.time);
35     date.setHours(objDate.hours);
36     date.setMinutes(objDate.minutes);
37     date.setSeconds(objDate.seconds);
38     return date.format("yyyy-MM-dd HH:mm:ss");
39 }
40 Date.prototype.format = function(format) {
41     /*
42      * format="yyyy-MM-dd hh:mm:ss";
43      */
44     var o = {
45         "M+" : this.getMonth() + 1,
46         "d+" : this.getDate(),
47         "h+" : this.getHours(),
48         "m+" : this.getMinutes(),
49         "s+" : this.getSeconds(),
50         "q+" : Math.floor((this.getMonth() + 3) / 3),
51         "S" : this.getMilliseconds()
52     };
53     if (/(y+)/.test(format)) {
54             format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4- RegExp.$1.length));
55         }
56     for (var k in o) {
57         if (new RegExp("(" + k + ")").test(format)){
58             format = format.replace(RegExp.$1, RegExp.$1.length == 1? o[k]:("00" + o[k]).substr(("" + o[k]).length));
59         }
60     }
61     return format;
62     
63 };

 

posted @ 2015-10-30 14:39  flay  阅读(287)  评论(0编辑  收藏  举报