Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JavaScript show me one day before my set date? [duplicate]

I'm trying see dates based off of some json data I have.

My code is:

var date = new Date(json.events[i].event.first_date);
alert(date);

Now, that json.events[i].event.first_date just returns the date in the format of yyyy-mm-dd.

I noticed, however that when I do the alert(date);, I'm shown the day before the date that the actual data says.

For example, json.events[0].event.first_date gives the date 2015-06-02 but the alert shows June 1, 2015.

I am getting my json from a url based somewhere in Germany and I am in the US. Could the date be messed up because of timezones?

like image 926
Jud Avatar asked Sep 03 '15 21:09

Jud


1 Answers

When you create date from string without timezone you get a date + timezone correction – if you're in USA then you have something like GMT-7 and you get the second of June minus 7 hours – the previous day. Try splitting your date and use new Date(2015, 7, 1) constructor and you'll get date you're expecting. String parse reference docs -https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

like image 186
La Faulx Avatar answered Sep 28 '22 18:09

La Faulx