Date.prototype.toString()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

toString() 方法,屬於 Date 例項,返回一個表示此日期根據本地時區解析後的字串。

試一試

const event = new Date("August 19, 1975 23:15:30");

console.log(event.toString());
// Expected output: "Tue Aug 19 1975 23:15:30 GMT+0200 (CEST)"
// Note: your timezone may vary

語法

js
toString()

引數

無。

返回值

表示給定日期的字串(格式請參見說明)。如果日期 無效,則返回 "Invalid Date"

描述

toString() 方法是 型別轉換協議 的一部分。由於 Date 物件有一個 [Symbol.toPrimitive]() 方法,因此當 Date 物件被隱式 轉換為字串 時,該方法始終優先於 toString()。然而,Date.prototype[Symbol.toPrimitive]() 在內部仍會呼叫 this.toString()

Date 物件重寫了 ObjecttoString() 方法。Date.prototype.toString() 返回根據本地時區解析的日期字串表示形式,包含日期和時間 — 它將 toDateString()toTimeString() 的字串表示連線起來,中間加一個空格。例如:“Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)”。

Date.prototype.toString() 必須在 Date 例項上呼叫。如果 this 值不是繼承自 Date.prototype,則會丟擲 TypeError

  • 如果只想獲取日期部分,請使用 toDateString()
  • 如果只想獲取時間部分,請使用 toTimeString()
  • 如果希望日期根據 UTC 而非本地時區進行解析,請使用 toUTCString()
  • 如果希望以更友好的格式(例如,本地化)顯示日期,請使用 toLocaleString()

示例

使用 toString()

js
const d = new Date(0);
console.log(d.toString()); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"

規範

規範
ECMAScript® 2026 語言規範
# sec-date.prototype.tostring

瀏覽器相容性

另見