Check out this code:

​var dateA = new Date("2012-01-01");​​​​​​​​​​​
var dateB = new Date("01-01-2012");

console.log(+dateA == +dateB); // false  

At first glance this may seem really odd. After I explain whats happening it will only seem a little odd.

They are both 12am Jan 1st, 2012. The difference is when you specify a string in the format YYYY-MM-DD, you get a date that is 12am in the GMT timezone and when you specify a date in the format DD-MM-YYYY, you get a date that is 12am in your current timezone.

So being that I am in Atlanta right now, if I run this code:

alert(new Date("01-01-2012"));  

This is what I get:

Sun Jan 01 2012 00:00:00 GMT-0500 (EST)

OK, thats expected, but when I run this:

alert(new Date("2012-01-01"));  

Then I get this:

Sat Dec 31 2011 19:00:00 GMT-0500 (EST)

Wait just a second! I specified that I wanted a date in the year 2012 and I get a date that is 2011 in return??? I was pretty alarmed when I first saw this, but upon further inspection I noticed that the time is 19:00:00 and the timezone is GMT-0500 (EST) and if you were to add the 5 hours the time would in fact be 12am Jan 1st.

So what's happening is, when you specify the date in that format, you are getting that date in UTC time, but when you are alerting it, it tells you the date in local time. So it subtracts 5 hours, not only changing the day but the month and year as well. If you were to specify you wanted the date in UTC though, it would be what you expected:

alert(new Date("2012-01-01").getFullYear()); // 2011  
alert(new Date("2012-01-01").getUTCFullYear()); // 2012  

Aren't timezones fun?

© 2017. All Rights Reserved.

Proudly published with Ghost