The toString()
method returns a string representing the specified Date
object.
dateObj.toString()
A string representing the given date.
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:
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.
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)
Specification | Status | Comment |
---|---|---|
ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.0. |
ECMAScript 5.1 (ECMA-262) The definition of 'Date.prototype.toLocaleTimeString' in that specification. | Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Date.prototype.toString' in that specification. | Standard | |
Unknown The definition of 'Date.prototype.toString' in that specification. | Unknown | Format of Date.prototype.toString is standardised. |
ECMAScript Latest Draft (ECMA-262) The definition of 'Date.prototype.toString' in that specification. | Draft |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | Yes | Yes | 1 | Yes | Yes | Yes |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | Yes | 4 | Yes | Yes | Yes |
Server | |
---|---|
Node.js | |
Basic support | Yes |
Object.prototype.toString()
Date.prototype.toDateString()
Date.prototype.toLocaleString()
Date.prototype.toTimeString()
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString