試一試
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 物件重寫了 Object 的 toString() 方法。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 |
瀏覽器相容性
載入中…