用 C# 的 DateTime 透過 JSON 傳到前端時,你收到的往往不是人類看得懂的日期字串,而是這種東西:
/Date(1354116249000)/
這串數字是「從 1970 年 1 月 1 日 00:00:00 UTC 到該時刻的毫秒數」,也就是所謂的 Unix 時間戳(毫秒版)。好消息是 JavaScript 的 Date 建構子可以直接吃這個數字。
var timestamp = "/Date(1354116249000)/";
var d = new Date(parseInt(timestamp.replace("/Date(", "").replace(")/", ""), 10));
console.log(d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate()
+ "日 " + d.getHours() + ":" + d.getMinutes());
// 輸出:2010年12月23日 10:53
兩個關鍵動作:先用 replace 把 /Date( 與 )/ 這層包裝拆掉,再用 parseInt 轉成數字送進 Date。切記不要把整串 /Date(...)/ 直接傳進去,那樣只會得到 Invalid Date。
另外注意 getMonth() 是 從 0 開始算的,所以要 +1 才是人類熟悉的月份。這是 JavaScript 日期處理最經典的陷阱。
如果目標是 2010-10-20 10:00:00 這種固定格式,寫一個小函式會比較乾淨:
function formatDate(now) {
var year = now.getFullYear();
var month = now.getMonth() + 1;
var date = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}
var d = new Date(1230999938);
alert(formatDate(d));
不過這個版本有個問題:月和日只有一位數時不會補零,會輸出 2010-1-5 而不是 2010-01-05。補上即可:
function pad(n) {
return n < 10 ? '0' + n : '' + n;
}
function formatDate(now) {
return now.getFullYear() + "-" + pad(now.getMonth() + 1) + "-" + pad(now.getDate())
+ " " + pad(now.getHours()) + ":" + pad(now.getMinutes()) + ":" + pad(now.getSeconds());
}
還有一個容易忽略的細節:範例用了 getYear() 的話要小心,它回傳的是「年份減 1900」,2010 年會得到 110。請一律使用 getFullYear()。
function format(dateStr) {
var d = new Date(parseInt(dateStr.replace(/\/Date\((\d+)\)\//, "$1"), 10));
return d.toLocaleString(); // 直接交給瀏覽器格式化
}
用一個正則 \/Date\((\d+)\)\/ 就能同時取出數字並驗證格式,比連續兩個 replace 更省事。
時區問題。/Date(...)/ 裡的毫秒數是 UTC 基準,而 getHours() 這類方法會依使用者本機時區回傳結果。同一個時間戳在台灣和美國會顯示不同的小時數。如果你要的是「伺服器時間」,該在後端先轉好字串再傳,或明確使用 getUTCHours() 系列並自行標註時區。
別忘了 decodeURIComponent。如果這個值來自網址參數,中文或特殊字元可能被編碼過,取值後記得解碼。
現代寫法。今天處理日期時間建議直接用 Intl.DateTimeFormat,它內建多語系與多時區支援:
new Intl.DateTimeFormat('zh-TW', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
}).format(new Date(1354116249000));
如果專案裡已有 dayjs 或 date-fns 這類輕量函式庫,用它們會更省心,也不必自己維護補零、時區這些細節。