本文介绍了两种在 JavaScript 中格式化日期时间的方法。第一种通过扩展 Date.prototype 实现通用的格式字符串替换,支持年、月、日、时分秒及季度的自定义组合;第二种为独立的 getNowFormatDate 函数,专门用于生成 yyyy-mm-dd 格式的当前日期字符串,并处理了月份和日期的补零逻辑及浏览器兼容性差异。
通用日期格式化方法
代码示例如下:
Date.prototype.format = function(format){
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;
}
//调用示例
var now = new Date();
var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
//调用方式2:
var testDate = new Date();
var testStr = testDate.format("YYYY年MM月dd日hh小时mm分ss秒");
alert(testStr);
//示例演示:
alert(new Date().Format("yyyy年MM月dd日"));
alert(new Date().Format("MM/dd/yyyy"));
alert(new Date().Format("yyyyMMdd"));
alert(new Date().Format("yyyy-MM-dd hh:mm:ss"));特定格式日期获取方法
JS格式化当前时间为yyyy-mm-dd格式
代码示例如下:
function getNowFormatDate()
{
var day = new Date();
var Year = 0;
var Month = 0;
var Day = 0;
var CurrentDate = "";
//时间初始化
//Year= day.getYear();//在Firefox下2008年显示108的bug
Year= day.getFullYear();//IE和Firefox均适用
Month= day.getMonth()+1;
Day = day.getDate();
//Hour = day.getHours();
// Minute = day.getMinutes();
// Second = day.getSeconds();
CurrentDate += Year + "-";
if (Month >= 10 )
{
CurrentDate += Month + "-";
}
else
{
CurrentDate += "0" + Month + "-";
}
if (Day >= 10 )
{
CurrentDate += Day ;
}
else
{
CurrentDate += "0" + Day ;
}
return CurrentDate;
} 此外可参考:JavaScript日期时间格式化函数