0

In javascript I tried this

new Date(Date.parse("2016-12-15"));

And it outputs a date object but with the date as Wed Dec 14 19:00:00 EST 2016. Why is it dec 14 when I expect it as dec 15?

Thanks

GG.
  • 21,083
  • 14
  • 84
  • 130
omega
  • 40,311
  • 81
  • 251
  • 474
  • 4
    Because of timezones. It's parsing the date as UTC but you are in EST so it's showing as the day before. – Jordan Soltman Dec 13 '16 at 21:27
  • How can I set it to be the timezone for EST time zone ((UTC-05:00) Eastern Time (US & Canada))? – omega Dec 13 '16 at 21:28
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse – Jordan Soltman Dec 13 '16 at 21:30
  • Yes, basically how can I make the conversion to date object relative to a certain timezone. – omega Dec 13 '16 at 21:30
  • the appropriate way of handling this correctly in a cross-browser way is to parse the date manually into its individual pieces and pass those directly to the date constructor instead of using Date.parse. that will ensure the same date will display across all browsers. – Mike Corcoran Dec 13 '16 at 21:31
  • I suggest using MomentJS –  Dec 13 '16 at 21:39

3 Answers3

0

You can create a date object from a specific UTC time using .Date.UTC() method, but then you have to pass the values individually:

new Date(Date.UTC(year, month, day, hour, minute, second));

A better and safer approach would be to use moment.js

Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
0

JavaScript dates don't contain a time zone. The date you are parsing is interpreted as December 15, 2016 at midnight UTC.

When you are converting it back to a string, it uses the time zone from your browser locale, and since you appear to be on the american east coast, the appropriate time zone is EST.

7pm EST equals midnight the next day in UTC.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
0

Parse is not a reliable way to parse your date...

Differences in assumed time zone

Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC (ES5 and ECMAScript 2015). Therefore Date objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted.

-- Source --

I think you should get the client date with its timezone and use a library like Moment.js to parse the date correctly.

David Gomez
  • 2,762
  • 2
  • 18
  • 28