I've been using the Javascript Date API for a calendar application, and I noticed that for every month between 3 and 9 (April and November) the methods Date.getDay() and Date.getUTCDay() return different results.
For each of these months, Date.getUTCDay() will consistently return the same as Date.getDay() - 1.
I eventually noticed this only happened when I built the dates with the default constructor. Once I tried using the Date.UTC() method to build the dates, everything went as expected.
Which is to say:
Date date = null; for (var month = 0; month < 12; month++) { date = new Date(2014, month, 1); if (date.getUTCDay() !== date.getDay()) { console.log(month); } } Will output: 3, 4, 5, 6, 7, 8 and 9.
Date date = null; for (var month = 0; month < 12; month++) { date = new Date(Date.UTC(2014, month, 1)); if (date.getUTCDay() !== date.getDay()) { console.log(month); } } Will not output anything.
I'm assuming it has something to do with DST, but I'd still like to have some deeper understading on what is happening and why.
Aside: I'm also assuming this is not something specifically related to Javascript, which is why I tagged the question with language-agnostic. Feel free to re-tag as appropriate.
Edit: Completely forgot to update the title after writing the question. I apologize.
Date.UTC()method to build the dates, everything went as expected." and "I'm assuming it has something to do with DST" collectively point you square at the answer. I'd imagine the docs fornew Date(y,m,d)will provide explicit confirmation.2014-12-04 01:00in UTC+02:00 is2014-12-03 23:00in UTC. If you use a library which represents dates by timestamps at midnight, then applying timezone conversion to dates changes the date since midnight can become before-midnight in another timezone.