Date.prototype.toString() 返回表示該 Date 對象的**字符串**,格式為瀏覽器實現相關的可讀日期時間字符串(通常為美式英語格式)。
dateObj.toString()
無參數。
日期時間字符串,格式類似:"Wed Jul 28 1993 14:39:07 GMT+0800 (中國標準時間)"
const date = new Date(1993, 6, 28, 14, 39, 7); // 月份 0-11,6=7月
console.log(date.toString());
// "Wed Jul 28 1993 14:39:07 GMT+0800 (中國標準時間)" (時區視環境而定)
// 當前時間
console.log(new Date().toString());
// "Tue Oct 15 2024 10:30:45 GMT+0800 (中國標準時間)"
| 方法 | 輸出示例 | 用途 |
|---|---|---|
toString() | "Wed Jul 28 1993 14:39:07 GMT+0800" | 默認調試、日誌輸出 |
toISOString() | "1993-07-28T06:39:07.000Z" | **標準化存儲/傳輸**(UTC,ISO 8601) |
toLocaleString() | "1993/7/28 下午2:39:07" | 本地化顯示(用戶界面) |
toDateString() | "Wed Jul 28 1993" | 僅日期部分 |
toTimeString() | "14:39:07 GMT+0800" | 僅時間部分 |
toUTCString() | "Wed, 28 Jul 1993 06:39:07 GMT" | UTC 時間字符串(HTTP 頭、Cookie) |
// 1. 調試日誌
console.log('創建時間:', createdAt.toString());
// 2. 快速生成時間戳字符串(非標準)
const timestamp = new Date().toString().replace(/[:\s]/g, '-');
// "Tue-Oct-15-2024-10-30-45-GMT+0800"
// 3. 序列化前轉換(推薦用 toISOString)
const data = {
createdAt: new Date().toISOString() // 標準格式
};
localStorage.setItem('data', JSON.stringify(data));
GMT+0800)toLocaleString() 配置選項或庫(date-fns, dayjs)Object.prototype.toString.call(date) 返回 "[object Date]",用於類型檢測date.toISOString()(UTC、ISO 8601、可直接 new Date() 解析)date.toLocaleString(locale, options) 或 dayjs/date-fnsconsole.log(date) 瀏覽器會自動調用 toString(),可直接輸出對象Date.toString() 是快速查看日期對象內容的便捷方法,但**切勿用於數據交換或持久化**,請使用標準化的 toISOString() 或成熟的日期庫。