Weird behavior of `new Date` in JavaScript

Viewed 69

I am not sure why it's working like this:

new Date('2020-10-06')
// Mon Oct 05 2020 20:00:00 GMT-0400 (Eastern Daylight Time) {}

new Date('2020-10-06 ')
// Tue Oct 06 2020 00:00:00 GMT-0400 (Eastern Daylight Time) {}

I want to get new Date('2020-10-06') as a Date object of the day(not previous day).

Could anyone give me an idea?

1 Answers

Your first example matches the only format that the Date object is required to parse, and which has clear rules around how to parse, including whether to treat it as UTC or not (because it's date-only, the answer is: yes, treat it as UTC; details here).

Your second example doesn't match that format (because Date doesn't trim the string), so it falls back on "...implementation-specific heuristics or implementation-specific date formats." In this case, it appears to treat the date as being in the local timezone, not UTC. But you couldn't rely on that cross-browser; another JavaScript engine might do something else.

Related