用 jQuery 或 fetch 從 ASP.NET 的 Web API/ASMX 取資料時,日期欄位常會出現 /Date(1401076829)/ 這種怪字串。它不是亂碼,而是「自 1970-01-01 UTC 起的毫秒數」被包了一層外殼,把外殼拿掉就能還原成真正的時間。
onload = function () {
var thisDateText = '/Date(1401076829)/';
document.write(getLocalTime(thisDateText));
};
function getLocalTime(dateText) {
// 先把 /Date( 與 )/ 這層外殼去掉
dateText = dateText.replace('/Date(', '').replace(')/', '');
// 此時 dateText 為純毫秒數字串
// 若要保留「2014年5月26日 下午12:00」的中文格式:
// return new Date(parseInt(dateText, 10)).toLocaleString();
// 要標準的 2014-5-26 12:00:29:
return new Date(parseInt(dateText, 10)).toLocaleString()
.replace(/年|月/g, '-')
.replace(/日/g, ' ')
.replace(/上午|下午/g, ' ');
}
有些老範例會寫 new Date(parseInt(dateText) * 1000),那是把「秒數」的舊格式當成輸入。.NET 的 /Date(...)/ 裡放的是毫秒,再乘 1000 會得到西元六萬多年的日期。判斷方式很簡單:數字的位數有 13 位就是毫秒,10 位才是秒。
用字串 replace 把中文年月日拆掉,會受瀏覽器語言地區影響(英文環境輸出的是 "5/26/2014 12:00:29 PM",replace 什麼都換不到)。與其依賴 toLocaleString 的輸出格式,不如自己組字串:
function parseAspNetDate(dateText) {
var ms = parseInt(String(dateText).replace(/\/Date\((\d+)\)\//, '$1'), 10);
if (isNaN(ms)) return null;
return new Date(ms); // 回傳 Date 物件,格式化交給呼叫端決定
}
function format(d) {
var p = function (n) { return n < 10 ? '0' + n : '' + n; };
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate())
+ ' ' + p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds());
}
console.log(format(parseAspNetDate('/Date(1401076829)/'))); // 2014-05-26 12:00:29
另外,含時區偏移的格式長得像 /Date(1401076829000+0800)/,這時要把後面的 offset 一併讀出來並換算,否則會有時差。
如果後端是你自己維護的,最建議的作法是改用 ISO 8601 字串輸出。在 ASP.NET 中設定 JSON.NET 的 DateFormatHandling.IsoDateFormat,前端拿到的就是 2014-05-26T12:00:29+08:00,new Date() 可直接解析、含時區資訊、跨語言環境都一致,省掉所有字串處理。