工作中常常会遇到后台返回的值是毫秒,这时候就需要前端根据需要转换一下时间格式;
1、换算年月日
function timeFormat(date) {
var format = 'yyyy-MM-dd';
var t = new Date(date);
var tf = function(i) {
return (i < 10 ? '0' : '') + i
};
var time = format.replace(/yyyy|MM|dd/g, function(a) {
switch (a) {
case 'yyyy':
return tf(t.getFullYear());
break;
case 'MM':
return tf(t.getMonth() + 1);
break;
case 'dd':
return tf(t.getDate());
break;
}
})
return time;
}
2、换算年月日 时分秒
function timeFormatT(date) {
var format = 'yyyy-MM-dd hh:mm:ss';
var t = new Date(date);
var tf = function(i) {
return (i < 10 ? '0' : '') + i
};
var time = format.replace(/yyyy|MM|dd|hh|mm|ss/g, function(a) {
switch (a) {
case 'yyyy':
return tf(t.getFullYear());
break;
case 'MM':
return tf(t.getMonth() + 1);
break;
case 'dd':
return tf(t.getDate());
break;
case 'hh':
return tf(t.getHours());
break;
case 'mm':
return tf(t.getMinutes());
break;
case 'ss':
return tf(t.getSeconds());
break;
}
})
return time;
}
3、时间的前后推移
function GetDateStr(AddDayCount) {
var dd = new Date();
dd.setDate(dd.getDate()+AddDayCount);
var y = dd.getFullYear();
var m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);
var d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();
return y+"-"+m+"-"+d;
}
GetDateStr(30)//往前推30天
GetDateStr(-30)//往后推30天