文章出處

  原文地址:http://www.cnblogs.com/zhangpengshou/archive/2012/07/19/2599053.html

  結合meizz的代碼做了適當調整。

Date.prototype.Format = function (fmt) {
    var that = this;
    var postfix = false;
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": function () {
            return postfix ? (that.getHours() % 12 == 0 ? 12 : that.getHours() % 12) : that.getHours();
        }, //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            if (RegExp.$1.length == 1 && RegExp.$1 == "h") postfix = true;
            var val = typeof (o[k]) == "function" ? o[k].apply(this) : o[k];
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (val) : (("00" + val).substr(("" + val).length)));
            
        }
    }
    return fmt + (postfix ? ((this.getHours() < 12) ? " AM" : " PM") : "");
}

// following are testing code
var Ld = "26-09-2014"; var Lt = "13:15:23"; var arrDateParts = Ld.split("-"); if (arrDateParts.length == 3) { var dayNum = arrDateParts[0]; var monthNum = arrDateParts[1]; var yearNum = arrDateParts[2]; var D = new Date(monthNum.concat("/", dayNum, "/", yearNum, ' ', Lt)); console.info(D.Format("M/dd/yyyy h:mm:ss")); }

  以上代碼可根據所提供的格式字符串以及時間來判斷是否需要添加AM/PM后綴。


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()