Date 物件提供了好幾個 toXxx 方法來輸出日期時間,格式各不相同。以下用同一個時間點逐一對照,最清楚。
toLocaleDateString() 與 toLocaleTimeString():
(new Date()).toLocaleDateString() + " " + (new Date()).toLocaleTimeString()
// 結果:2008年1月29日 16:13:11
這組方法的特色是會依使用者所在的地區設定輸出,因此不同語言環境看到的格式會不一樣。要固定格式,可以傳入 locale 參數:toLocaleDateString('zh-TW')。
toDateString() 與 toTimeString():
(new Date()).toDateString() + " " + (new Date()).toTimeString()
// 結果:Tue Jan 29 2008 16:13:11 UTC+0800
輸出的是英文的星期與月份縮寫,時間部分會帶上時區標示。適合需要人類可讀、又不希望受地區設定影響的場合。
toGMTString():
(new Date()).toGMTString()
// 結果:Tue, 29 Jan 2008 08:13:11 UTC
注意時間從 16:13 變成 08:13,這就是八小時的時區差。要特別留意 toGMTString() 已被標示為過時,請改用下面的 toUTCString(),兩者輸出相同。
toUTCString():
(new Date()).toUTCString()
// 結果:Tue, 29 Jan 2008 08:13:11 UTC
toString():
(new Date()).toString()
// 結果:Tue Jan 29 16:13:11 UTC+0800 2008
這個格式由實作自行決定,不同瀏覽器可能略有差異,因此不適合拿來做資料比對或傳輸。
toISOString():輸出 2008-01-29T08:13:11.000Z。這是目前最推薦的標準格式,字母排序即等於時間排序,且明確帶有 UTC 標記,適合存檔、API 傳輸與跨系統交換。
toDateString 以外的組合:若需要自訂格式(例如 2008/01/29 16:13),標準做法是使用 Intl.DateTimeFormat:
new Intl.DateTimeFormat('zh-TW', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', hour12: false
}).format(new Date());
它同時處理了地區慣例、補零與 12/24 小時制的問題,比手動的字串拼接可靠得多。
最後提醒一個常見誤解:new Date("2008-01-29") 這種只給日期的寫法會被當成 UTC 解析,而 new Date(2008, 0, 29) 則是以本地時間建立。在跨時區環境下,這個差異可能讓日期差一天,處理時要格外小心。