1

I have a function that takes in various (valid) date strings and outputs a JavaScript Date.

Most strings return the expected date, however, when an ISO formatted date is passed in (YYYY/MM/DD), The user's timezone offset is SUBTRACTED from the date.

So:

new Date("9/1/2017") //returns Fri Sep 01 2017 00:00:00 GMT-0400 (Eastern Daylight Time)

but

new Date("2017-09-01") //returns Thu Aug 31 2017 20:00:00 GMT-0400 (Eastern Daylight Time)

I've found that by forcing the timezone by adding the time - "T00:00:00" to the ISO date forces it to the correct date & time, but was wondering why JavaScript subtracts out the timezone only for ISO dates.

DShultz
  • 4,381
  • 3
  • 30
  • 46

1 Answers1

1

Note that Chrome handles those two datestrings you offer as examples differently but firefox does not. MDN is a good resource on the differences.

In any case, parsing date strings is not recommended unless they are ISO 8601 in which case they are interpreted as UTC consistently across browsers. Supplying integer arguments to the Date constructor is also consistent.

Jared Smith
  • 19,721
  • 5
  • 45
  • 83
  • "*Consistently across browsers*" is only true for recent browsers. Treating date-only forms as UTC is inconsistent with ISO 8601. You have to wonder what the ECMAScript authors were thinking. – RobG Oct 04 '17 at 22:32
  • @RobG pretty sure they were thinking "I've only got ten days to get this done" :) – Jared Smith Oct 05 '17 at 11:00