3

I am creating a date with new Date(). When I do this, it is subtracting a day. Here is the code:

var dateString = "2016-04-10";
var date = new Date(dateString);

// date = Sat Apr 09 2016 18:00:00 GMT-0600 (MDT)

What do I misunderstand? Why is the date not Apr 10 2016? How do I make this work properly?

5
  • try new Date(2016,4,10); Commented Apr 18, 2016 at 15:28
  • 1
    Uh, the date you have there is midnight (0:00) of Apr 10 2016? Commented Apr 18, 2016 at 15:28
  • I am receiving the date formatted in the above manner. I need to make that format work? Is there a way to make that happen? Commented Apr 18, 2016 at 15:29
  • 1
    @jhamm: The date object you have is correct. It's just your output format that is timezone-dependent - use .toUTCString() instead of .toString() Commented Apr 18, 2016 at 15:30
  • This question has been asked many, many times before. The TC39 committee apparently thought treating ISO 8601 format dates as UTC when the standard treats them as local would avoid confusion. Commented Apr 18, 2016 at 23:26

1 Answer 1

9

Your timezone is GMT-6 (as revealed by the GMT-0600 (MDT) in the output you've provided). Therefore the date which gets generated is offset by -6 hours. In this case, midnight minus 6 hours is 6PM on the previous day.

If you call date.toISOString(), you'll see that the UTC time is "2016-04-10T00:00:00.000Z" as expected.

Sign up to request clarification or add additional context in comments.

1 Comment

"As expected" only if you are aware of the inconsistencies of ECMAScript 2015 date string parsing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.