Date.prototype.toString() - JavaScript 编辑

The toString() method returns a string representing the specified Date object.

Syntax

dateObj.toString()

Return value

A string representing the given date.

Description

Date instances inherit their toString() method from Date.prototype, not Object.prototype. Date.prototype.toString() returns a string representation of the Date in the format specified in ECMA-262 which can be summarised as:

  • Week day: 3 letter English week day name, e.g. "Sat"
  • space
  • Month name: 3 letter English month name, e.g. "Sep"
  • space
  • Date: 2 digit day in month, e.g. "01"
  • space
  • Year: 4 digit year, e.g. "2018"
  • space
  • Hour: 2 digit hour of day, e.g. "14"
  • colon
  • Minute: 2 digit minute of hour, e.g. "53"
  • colon
  • Second: 2 digit second of minute, e.g. "26"
  • space
  • The string "GMT"
  • Timezone offset sign, either:
    • "+" for positive offsets (0 or greater)
    • "-" for negative offsets (less than zero)
  • Two digit hour offset, e.g. "14"
  • Two digit minute offset, e.g. "00"
  • Optionally, a timezone name consisting of:
    • space
    • Left bracket, i.e. "("
    • An implementation dependent string representation of the timezone, which might be an abbreviation or full name (there is no standard for names or abbreviations of timezones), e.g. "Line Islands Time" or "LINT"
    • Right bracket, i.e. ")"

E.g. "Sat Sep 01 2018 14:53:26 GMT+1400 (LINT)"

Until ECMAScript 2018 (edition 9), the format of the string returned by Date.prototype.toString was implementation dependent. Therefore it should not be relied upon to be in the specified format.

The toString() method is automatically called when a date is to be represented as a text value, e.g. console.log(new Date()), or when a date is used in a string concatenation, such as var today = 'Today is ' + new Date().

toString() is a generic method, it does not require that its this is a Date instance. However, it must have an internal [[TimeValue]] property that can't be constructed using native javascript, so it's effectively limited to use with Date instances. If called on a non–Date instance, a TypeError is thrown.

Examples

Using toString()

The following assigns the toString() value of a Date object to myVar:

var x = new Date();
var myVar = x.toString(); // assigns a string value to myVar in the same format as:
                          // Mon Sep 08 1998 14:36:22 GMT-0700 (PDT)

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'Date.prototype.toString' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:80 次

字数:6226

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文