Dilip Rajkumar
Dilip Rajkumar

Reputation: 7074

JS Date to ISO String Strange behavior

new Date("2018-09-9").toISOString()

This gives 2018-09-09T04:00:00.000Z

Where as

new Date("2018-09-19").toISOString()

Gives "2018-09-19T00:00:00.000Z"

I am from US so 4:00:00 seems correct UTC time, but if I give any date greater than 9 it gives 00:00:00 am I missing anything?

Upvotes: 0

Views: 232

Answers (1)

Felix B.
Felix B.

Reputation: 174

This is a correct behaviour. See the Reference for Javacript Date: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

Your second version is using the format ISO 8601 format YYYY-MM-DD which is treated as UTC. If you use 2018-09-09 instead of 2018-09-9 in your first example it will also be treated as UTC instead of local time.

Upvotes: 1

Related Questions