Date.prototype.format =function(format)
{
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;
}
// 时间格式化
Date.prototype.format =function(){
var format=null;
var now = new Date();
var o = {
"M" : this.getMonth()+1, // month
"d" : this.getDate(), // day
"h" : this.getHours(), // hour
"m" : this.getMinutes(), // minute
"s" : this.getSeconds(), // second
};
if(this.getFullYear() == now.getFullYear()){
if(o.M == now.getMonth()+1){
if(o.d == now.getDate())
format = "今天 " + (o.h<10?"0"+ o.h:o.h) + ":" + (o.m<10?"0"+o.m:o.m) + ":"
+ (o.s<10?"0"+o.s:o.s);
else if(o.d == now.getDate()-1)
format = "昨天 " + (o.h<10?"0"+ o.h:o.h) + ":" + (o.m<10?"0"+o.m:o.m) + ":"
+ (o.s<10?"0"+o.s:o.s);
else format = o.M + "月" + o.d + "日";
}else{
format = o.M + "月" + o.d + "日";
}
}else{
format = this.getFullYear() + "年" + o.M + "月" + o.d + "日";
}
delete now;
return format;
};
// 时间格式化
Date.prototype.format =function(){
var now=new Date().valueOf(),
formatFunctionCache={
'Seconds':function(dateTime,spendSeconds){
return parseInt(spendSeconds)+'秒钟前';
},
'Minutes':function(dateTime,spendSeconds){
return parseInt(spendSeconds/60)+'分'+parseInt(spendSeconds%60)+'秒前';
},
'Hours':function(dateTime,spendSeconds){
return parseInt(spendSeconds/(60*60))+'小时前';
},
'Days':function(dateTime,spendSeconds){
return parseInt(spendSeconds/(60*60*24))+'天前';
},
'Month':function(dateTime,spendSeconds){
return parseInt(spendSeconds/(60*60*24*30))+'个月前';
}
};
var spendSeconds=(now- this.valueOf())/(1000),
func;
if(spendSeconds<(60*60*24)){//一天之内
if(spendSeconds<60){//一分钟之内
func=formatFunctionCache['Seconds'];
}else if(spendSeconds<60*60){//一小时之内
func=formatFunctionCache['Minutes'];
}else{//一天之内
func=formatFunctionCache['Hours'];
}
}else if(spendSeconds<60*60*24*30){//一个月之内
func=formatFunctionCache['Days'];
}else{//N个月之前
func=formatFunctionCache['Month'];
}
// ...
return func(this,spendSeconds);
}
以上代码必须先声明,然后在使用。使用方法:
var d =new Date().format('yyyy-MM-dd');
本文介绍如何利用JavaScript实现日期时间的格式化,包括时间显示为今天、昨天或具体日期,并提供了时间间隔表达的函数,适用于展示时间差。

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



