js时间对象的格式化

 1 /**
 2  * 时间对象的格式化;
 3  */
 4 Date.prototype.format = function(format,now) {
 5     /*
 6      * eg:format="yyyy-MM-dd hh:mm:ss";
 7      */
 8 
 9     var d = now ? (new Date(Date.parse(now.replace(/-/g,   "/")))) : this;
10     var o = {
11         "M+" : d.getMonth() + 1, // month
12         "d+" : d.getDate(), // day
13         "h+" : d.getHours(), // hour
14         "m+" : d.getMinutes(), // minute
15         "s+" : d.getSeconds(), // second
16         "q+" : Math.floor((d.getMonth() + 3) / 3), // quarter
17          "N+" : ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"][d.getDay()],
18         "S" : d.getMilliseconds()// millisecond
19     }
20 
21     if (/(y+)/.test(format)) {
22         format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4
23                         - RegExp.$1.length));
24     }
25 
26     for (var k in o) {
27         if (new RegExp("(" + k + ")").test(format)) {
28             format = format.replace(RegExp.$1, RegExp.$1.length == 1
29                             ? o[k]
30                             : ("00" + o[k]).substr(("" + o[k]).length));
31         }
32     }
33     return format;
34 }
35 console.log(new Date().format("yyyy-MM-dd N",'2012-05-18 10:07:19'))
/**
 * 时间对象的格式化(JQuery版);
 */
(function($) {
$.fn.dateFormat= function(format) {
        var now = $(this).text();
        var d = now ? (new Date(Date.parse(now.replace(/-/g,   "/")))) : (new Date());
    var o = {
        "M+" : d.getMonth() + 1, // month
        "d+" : d.getDate(), // day
        "h+" : d.getHours(), // hour
        "m+" : d.getMinutes(), // minute
        "s+" : d.getSeconds(), // second
        "q+" : Math.floor((d.getMonth() + 3) / 3), // quarter
         "N+" : ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"][d.getDay()],
        "S" : d.getMilliseconds()// millisecond
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4
                        - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                            ? o[k]
                            : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};
})(jQuery);

console.log($('<p>2012-04-18 10:07:19</p>').dateFormat("yyyy-MM-dd N"))
posted @ 2012-05-18 10:09  无嗔  阅读(1521)  评论(0编辑  收藏  举报