Home > Net >  What are the circumstances when toString works on a date while toISOString does not work?
What are the circumstances when toString works on a date while toISOString does not work?

Time:09-08

Works:

const date = new Date();
temp = date.toISOString();

Doesn't work:

const date = new Date();
temp = date.setDate(date.getDate() - date.getDay()).toISOString();

Works too:

const date = new Date();
temp = date.setDate(date.getDate() - date.getDay()).toString();

What may be the reason for toISOString() not working?

CodePudding user response:

Because .toString() can be called on almost any value while .toISOString() can only be called on Date objects1.

This code:

const date = new Date();
temp = date.setDate(date.getDate() - date.getDay()).toISOString();

is effectively the same as

const date = new Date();
const setDateReturnValue = date.setDate(date.getDate() - date.getDay());
setDateReturnValue.toISOString();

Note that date and setDateReturnValue hold two different values. The date is the Date object and setDateReturnValue is the return value of Date.prototype.setDate(), which is a number.

A number doesn't have a .toISOString() method, which is what is causing the error. A Date does have a .toISOString() method, which is why your first code snippet works fine.

Both a Date and a number have a .toString() method2, which is why those work fine, but do realize that the string they return is different in a different format. (The number will return the number as a string, where the date will return something like "Wed Sep 07 2022 16:17:40 GMT 0200 (Central European Summer Time)")

[1]: Unless of course you or a library defines this function for different types.
[2]: Technically speaking: a number a primitive and as such, doesn't have a .toString() method (or any method for that matter), but when calling a method on a number, it will be boxed into a Number object, which does have a .toString() method.

  • Related