I researched about converting date into string in ISO format, and I found two methods to do that giving me the same result '2022-07-29T06:46:54.085Z':
(new Date()).toISOString()JSON.parse(JSON.stringify(new Date()))Question:
JS make two approaches/algorithms of converting date or just one function code just call on different object JSON or Date, If So Which one is the best to use?First of all: less code, easier to maintain
So, new Date().toISOString() is simplest way to return string in ISO format.
Regarding question:
No. The output is the same, because of JSON.stringify logic underneath that returns:
JSON.stringify(new Date())
'"2022-07-29T18:58:14.411Z"'
Because:
The instances of Date implement the toJSON() function by returning a string (the same as date.toISOString()). Thus, they are treated as strings.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
(new Date).toJSON()
'2022-07-29T18:58:14.411Z'
JSON.parse(JSON.stringify(new Date())) is just the same as new Date().toJSON(). And in the docs for that method we can see
Calling
toJSON()returns a string (usingtoISOString()) representing theDateobject's value.
So they're having exactly the same result, calling toISOString() directly is just much more straightforward.
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