JS格式化时间戳

 1 /* 
 2 * 格式化日期
 3 * 如:format = "yyyy-MM-dd hh:mm:ss"; 
 4 */
 5 Date.prototype.format = function (format) {
 6     var o = {
 7         "M+": this.getMonth() + 1,
 8         "d+": this.getDate(),
 9         "h+": this.getHours(),
10         "m+": this.getMinutes(),
11         "s+": this.getSeconds(),
12         "q+": Math.floor((this.getMonth() + 3) / 3),
13         "S+": this.getMilliseconds()
14     }
15 
16     if (/(y+)/.test(format)) {
17         format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4
18                 - RegExp.$1.length));
19     }
20 
21     for (var k in o) {
22         if (new RegExp("(" + k + ")").test(format)) {
23             var formatStr = "";
24             for (var i = 1; i <= RegExp.$1.length; i++) {
25                 formatStr += "0";
26             }
27 
28             var replaceStr = "";
29             if (RegExp.$1.length == 1) {
30                 replaceStr = o[k];
31             } else {
32                 formatStr = formatStr + o[k];
33                 var index = ("" + o[k]).length;
34                 formatStr = formatStr.substr(index);
35                 replaceStr = formatStr;
36             }
37             format = format.replace(RegExp.$1, replaceStr);
38         }
39     }
40     return format;
41 }  

 

posted @ 2014-04-04 11:26  lcyan  阅读(207)  评论(0编辑  收藏  举报