Almir Sarajčić
Almir Sarajčić

Reputation: 1570

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?

Upvotes: 39

Views: 11624

Answers (3)

Mizstik
Mizstik

Reputation: 666

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)

Upvotes: 40

smash
smash

Reputation: 366

Internally, toJSON() calls toISOString() if it's available, so no difference.

15.9.5.44 Date.prototype.toJSON ( key )

This function provides a String representation of a Date object for use by JSON.stringify (15.12.3).

When the toJSON method is called with argument key, the following steps are taken:

  1. Let O be the result of calling ToObject, giving it the this value as its argument.

  2. Let tv be ToPrimitive(O, hint Number).

  3. If tv is a Number and is not finite, return null.

  4. Let toISO be the result of calling the [[Get]] internal method of O with argument "toISOString".

  5. If IsCallable(toISO) is false, throw a TypeError exception.

  6. Return the result of calling the [[Call]] internal method of toISO with O as the this value and an empty argument list.

Upvotes: 35

user1726343
user1726343

Reputation:

JSON date format follows ISO 8601, which is what toISOString produces as well. There is no functional difference between the values returned by either method.

Upvotes: 3

Related Questions