一个格式化日期和时间的JavaScript类库

  原文地址: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后缀。

上一篇:Linux下diff打补丁方法


下一篇:[转]Java中的对象和对象引用实例浅析