在處理時間格式時,特别是通過json序列化datetime類型,傳回給前端進行展示,你會發現的字元串帶T。
例如:2017-09-05T13:08:56.080
在時間和日期之間會幫我們加個字母大些T,那如何解決呢?
一、提前在後端處理時間格式
将datetime類型轉換成string類型,不要以datetime類型進行json序列化,這樣可以避免問題。
二、在前端通過js進行格式
首先我們擴充new Date的方法:pattern
Date.prototype.pattern = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小時
"H+": this.getHours(), //小時
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
var week = {
"0": "\u65e5",
"1": "\u4e00",
"2": "\u4e8c",
"3": "\u4e09",
"4": "\u56db",
"5": "\u4e94",
"6": "\u516d"
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
if (/(E+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
};
其次:
var createTime="2017-09-05T13:08:56.080";
var date=new Date(createTime.replace('T', " ")).pattern("yyyy-MM-dd hh:mm:ss")
說明:先将字元T替換成“ ”空格,也就是時間2017-09-05 13:08:56.080,然後再進行格式化,轉換自己需要的格式:yyyy-MM-dd hh:mm:ss