I was checking how to display JavaScript date in the following format: YYYY-MM-DDTHH:mm:ss.sssZ
, but I saw two methods doing this: .toJSON() and .toISOString(). Is there some real difference between them?
The date. toISOString() method is used to convert the given date object's contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ). The date object is created using date() constructor.
toJSON() calls the object's toISOString() method, which returns a string representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor or Date.
Definition and Usage The toISOString() method returns a date object as a string, using the ISO standard. The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ.
The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .
One convenient difference is that if you have an invalid date, .toJSON()
will output null
. However, .toISOString()
's behavior can vary. In firefox this outputs a string "Invalid Date"
but in chrome it raises an exception.
Edit: Recent versions of Firefox have fixed the behavior to be the same as chrome (raising exception). However, the difference between .toJSON() and .toISOString() remains. (outputting null vs. raising exception)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With