從 C# 後端回傳的日期欄位,經過 JSON 序列化之後會變成 /Date(1290371638000)/ 這種形式,前端直接顯示並不是人能讀的日期。當然不可能為了這個把全部日期欄位都改成 string,比較合理的做法是在前端寫一個擴充函式來處理。
先把 /Date( 與 )/ 去掉,若殘留時區偏移(如 +08:00)也一併裁掉,剩下的就是毫秒數,丟給 Date 建構子即可。
function ChangeDateFormat(jsondate) {
jsondate = jsondate.replace("/Date(", "").replace(")/", "");
if (jsondate.indexOf("+") > 0) {
jsondate = jsondate.substring(0, jsondate.indexOf("+"));
} else if (jsondate.indexOf("-") > 0) {
jsondate = jsondate.substring(0, jsondate.indexOf("-"));
}
var date = new Date(parseInt(jsondate, 10));
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear() + "年" + month + "月" + currentDate + "日 " +
date.getHours() + ":" + date.getMinutes();
}
// 呼叫
ChangeDateFormat(data[i].arrDate);
$.ajax({
type: "Get",
dataType: "json",
url: "/UserInfo/GetUserWithdraw",
data: { id: id },
success: function (data) {
var result = html.replace(reg, function (node, key) {
return {
'Money': data.Money,
'AddTime': ChangeDateFormat(data.AddTime),
'CashTime': data.CashTime
}[key];
});
TsingdaTips.ask({
msg: result, show_btn: false, title: "提現申請詳情"
});
}
});
如果專案裡各處都需要格式化,與其每個地方寫一次字串拼接,不如做一次擴充。以下版本支援 yyyy、MM、dd、hh、mm、ss、季度 q 與毫秒 S:
/**
* 時間物件格式化
* eg: format = "YYYY-MM-dd hh:mm:ss"
*/
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 testDate = new Date();
var testStr = testDate.format("YYYY年MM月dd日hh小時mm分ss秒");
alert(testStr);
搭配起來,處理 /Date()/ 就只剩兩行:先取出毫秒數建 Date 物件,再呼叫 format。另外值得注意的一點是,若後端採用 .NET 的相關設定讓日期直接序列化成 ISO 8601 字串(例如 2024-05-01T08:30:00),前端就不必再做任何清理,這是比字串切割更省事的方向,值得在 API 設計階段就跟後端協調。