用起来挺方便的javascript下Date对象的时间格式化函数
不得在那里找到的了,感谢原作者提供的这么好的东西.这个函数我一直在用,用起来也很方便,分享分享!!!.
/**
* 时间对象的格式化;
*/
Date.prototype.format = function(format){
/*
* eg:format="yyyy-MM-dd hh:mm:ss";
*/
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.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(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;
}
使用方法:
var testDate = new Date();
var testStr = testDate.format("yyyy年MM月dd日hh小时mm分ss秒");
alert(testStr);
不得在那里找到的了,感谢原作者提供的这么好的东西.这个函数我一直在用,用起来也很方便,分享分享!!!.
/**
* 时间对象的格式化;
*/
Date.prototype.format = function(format){
/*
* eg:format="yyyy-MM-dd hh:mm:ss";
*/
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.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(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;
}
使用方法:
var testDate = new Date();
var testStr = testDate.format("yyyy年MM月dd日hh小时mm分ss秒");
alert(testStr);
本文介绍了一个实用的JavaScript Date对象扩展方法,该方法可以方便地将日期格式化为指定的格式字符串,例如yyyy年MM月dd日hh小时mm分ss秒。此扩展方法能够很好地处理各种日期和时间字段,并提供了灵活的格式定制选项。

被折叠的 条评论
为什么被折叠?



