首页 > 代码库 > 格式化日期

格式化日期

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+)/i.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"));

function formatterTime(date,showtime){
var dataTime=new Date(date);
var myDate=new Date();
var dffdate=myDate.getDate()-dataTime.getDate();
var dffyear=myDate.getFullYear()-dataTime.getFullYear(); 
var dffmonth=myDate.getMonth()-dataTime.getMonth();
//var iDays = parseInt(Math.abs(myDate - dataTime ) / 1000 / 60 / 60 /24);//把相差的毫秒数转换为天数 
//alert(iDays+":"+myDate.getDate()+":"+dataTime.getDate());
if(dffyear!=0){
dffdate=dataTime.getFullYear();
return dffdate;
}else if(dffmonth!=0){
dffdate=dataTime.format("MM/dd");
return dffdate;
}else if(dffdate==0){
dffdate = dataTime.format("hh:mm");
return dffdate;
}else if((1<=dffdate && dffdate<2)){
dffdate=‘昨天‘;
return dffdate;
}else if(2 <= dffdate && dffdate < 3){
if(myDate.getDay()<2){
dffdate = "周" + "日一二三四五六".split("")[myDate.getDay()+5];
}else{
dffdate = "周" + "日一二三四五六".split("")[myDate.getDay()-2];
}
return dffdate;
}else if(dffdate >= 3){
var _f = "MM/dd";
if(showtime){
_f+=" hh:mm";
}
dffdate=dataTime.format(_f);
return dffdate;
}
}
console.log(Date.now())
console.log(formatterTime(Date.now()))

格式化日期