Javascript中Date对象的格式化

时间:2024-01-15 20:45:38

很多语言中都带有日期的格式化函数,而Javascript中却没有提供类似的方法。
之前从某位前人的帖子中发现了下面的代码,感觉非常简洁,存留备用。

/**
* 时间对象的格式化;
*/
Date.prototype.format = function (format) {
/*
示例
var d=new Date();
d.format("YYYY-MM-dd hh:mm:ss");
结果:"2014-01-02 12:34:56"
*/
var o = {
"M+": this.getMonth() + 1, // 月
"d+": this.getDate(), // 日
"h+": this.getHours(), // 小时
"m+": this.getMinutes(), // 分钟
"s+": this.getSeconds(), // 秒
"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
"S": this.getMilliseconds() // 毫秒
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.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;
}