javascript按指定格式将Date对象转换为日期时间字符串
下面代码将扩展javascript Date对象,为Date对象添加一个format方法,类似于php的date函数,填补了javascript格式日期时间对象功能不足的遗憾:
//对Date的扩展,将 Date 转化为指定格式的字符串
//年(y)、月(m)、日(d)、星期(w)、小时(h)、分(i)、秒(s)、毫秒(u)
//用法:new Date().format("yyyy-mm-dd hh:ii:ss.u") ==> 2016-10-28 23:17:49.085
Date.prototype.format = function( format ) {
if ( typeof format !== "string" ) format = 'yyyy-mm-dd hh:ii:ss';
function fillZore(num, len) {
while(num.toString().length<len){
num = '0'+num;
}
return num;
}
var Week = ['日','一','二','三','四','五','六'];
format=format.replace(/yyyy|YYYY/,this.getFullYear());
format=format.replace(/yy|YY/, fillZore(this.getYear() % 100, 2));
format=format.replace(/mm|MM/, fillZore(this.getMonth()+1, 2));
format=format.replace(/m|M/g, this.getMonth()+1);
format=format.replace(/dd|DD/, fillZore(this.getDate(), 2));
format=format.replace(/d|D/g,this.getDate());
format=format.replace(/w|W/g, Week[this.getDay()]);
format=format.replace(/hh|HH/, fillZore(this.getHours(), 2));
format=format.replace(/h|H/g, this.getHours());
format=format.replace(/ii|II/, fillZore(this.getMinutes(), 2));
format=format.replace(/i|I/g, this.getMinutes());
format=format.replace(/ss|SS/, fillZore(this.getSeconds(), 2));
format=format.replace(/s|S/g, this.getSeconds());
format=format.replace(/u|U/g, fillZore(this.getMilliseconds(), 3));
return format;
}用法://2016-10-28 23:17:49.085
new Date().format("yyyy-mm-dd hh:ii:ss.u")
//2011年01月02日10时22分33秒
new Date("2011/01/02 10:22:33").format("yyyy年mm月dd日hh时ii分ss秒");
//2016-10-28
new Date().format("yyyy-mm-dd");
//22:53
new Date().format("hh:ii");