有时我们需要对日期格式化,这时可以利用javascript 的prototype机制进行扩展。
如下,我们为Date对象增加了一个Format方法,接受一个格式化参数,返回格式化后的日期字符串。
Date.prototype.Format = function (fmt) { //author: meizz
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(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
我们可以像使用java日期格式化一样来来使用这个方法。
new Date().Format("yyyy-MM-dd")
new Date().Format("yyyy-MM-dd HH:mm:ss")