1

If right now in my devtools console I type:

new Date('2018-12-29')

It returns:

Fri Dec 28 2018 16:00:00 GMT-0800 (Pacific Standard Time)

Why does that happen and what's the right way to fix this?

Does this have to do with timezones? How can I make sure it works properly for all my users?

benvc
  • 14,448
  • 4
  • 33
  • 54
lumenwrites
  • 1,287
  • 4
  • 18
  • 35

1 Answers1

2

From the JavaScript Date docs:

If at least two arguments are supplied, missing arguments are either set to 1 (if the day is missing) or 0 for all others

Also from the dateString parameter description in the docs:

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

Since you are passing an ISO 8601 format string and there are no time elements in your date string, it is filling those parameters with zeros and creating a date object in UTC like 2018-12-29T00:00:00.000Z and then the browser converts it to your local time, which in your case is 8 hours behind and on the previous day in the Pacific Time Zone.

benvc
  • 14,448
  • 4
  • 33
  • 54