Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Date.toJSON() and Date.toISOString()

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?

like image 512
Almir Sarajčić Avatar asked Apr 24 '13 17:04

Almir Sarajčić


People also ask

What is date toISOString?

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.

What does toJSON() do?

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.

What is toISOString()?

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.

Does toISOString convert to UTC?

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 .


1 Answers

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)

like image 109
Mizstik Avatar answered Sep 29 '22 00:09

Mizstik