1

I am completely baffled on what is happening with my javascript date. Here is my javascript:

toDate(date) {
  return date instanceof Date ? date : new Date(date)
}

When I pass the string "2016-12-01" to this function, I get this for my date

Wed Nov 30 2016 17:00:00 GMT-0700 (MST)

I am not passing in timezone information, just the string shown above. When I type the same code into my console, I get the same behavior.

enter image description here

Here is another example when I pass in timezone information where the same thing happens.

enter image description here

This is happening Chrome version 55.0.2883.75 (64-bit).

I tested in Firefox 50.0.2 and I am not having this issue.

Any ideas?

jhamm
  • 24,124
  • 39
  • 105
  • 179

2 Answers2

1

Do this instead:

new Date("2016-12-01".split("-"))

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.

from MDN

jwerre
  • 9,179
  • 9
  • 60
  • 69
0

If you check out the MDN documentation for the Javascript Date, you will find this warning below the documentation for passing a datestring to the Date constructor:

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.

That means that if you pass the date string "2016-12-01", the Date constructor will assume that you mean Midnight December 1st, 2016 UTC, but will then convert the date to your local timezone.

You appear to be on MST (like me!), which is 8 hours behind UTC time. So converting Midnight December 1st, 2016 UTC to MST would be 5PM November 30th, 2016!

chester
  • 297
  • 2
  • 13