大网数据广告活动
Web 标准与前端开发

Date.prototype.toString()

· 52CE 我爱测

**`toString()`** 方法返回一个字符串,以本地的时区表示该 Date 对象。

toString() 方法返回一个字符串,以本地的时区表示该 Date 对象。

JavaScript Demo: Date.toString()

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

语法

toString()

返回值

一个表示给定 date 对象的字符串。

描述

Date 对象覆盖了 Object 对象的 toString() 方法。Date.prototype.toString() 返回一个字符串,并以本地时区表示该 Date 对象,包含日期和时间——将 toDateString() 和 toTimeString() 通过一个空格拼接起来。

例如:“Thu Jan 01 1970 12:42:04 GMT+0800 (中国标准时间)”。

当 Date 被强制转换为字符串时,toString() 方法会被自动调用,例如:const today = 'Today is ' + new Date()。

Date.prototype.toString() 必须在 Date 实例上调用,如果 this 的值不是继承自 Date.prototype,则抛出 TypeError。

  • 如果你只想获取日期,请使用 toDateString()。
  • 如果你只想获取时间,请使用 toTimeString()。
  • 如果你想要获取 UTC 时间而非本地时间,请使用 toUTCString()。
  • 如果你想要以对用户更加友好的格式(例如,本地化)输出字符串,请使用 toLocaleString()。

示例

使用 toString()

const x = new Date();
console.log(x.toString()); // Wed Sep 09 1998 05:36:22 GMT+0800 (中国标准时间)

规范

浏览器兼容性

参见

  • Object.prototype.toString()
  • Date.prototype.toDateString()
  • Date.prototype.toLocaleString()
  • Date.prototype.toTimeString()

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。