1

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.

  • I'm not sure what's holding you back from working this out yourself, you seem to have all the pieces: "every month between 3 and 9 (April and November) " and "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." and "I'm assuming it has something to do with DST" collectively point you square at the answer. I'd imagine the docs for new Date(y,m,d) will provide explicit confirmation. – AakashM Dec 4 '14 at 15:21
  • 1
    2014-12-04 01:00 in UTC+02:00 is 2014-12-03 23:00 in 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. – CodesInChaos Dec 4 '14 at 15:21
2

You're constructing dates based on midnight local time. During daylight savings time, which UTC does not follow, midnight local time is the same as 11 p.m. the day before UTC time, if your local time zone is set to London\Western Europe time.

  • I could swear I tried the exact same code but with new Date(2014, month, 1, 10) to check exactly for that, and still got the different days. But now that I tried it again I got the same days. I must have made an error while trying that case and didn't notice. Now I feel kind of dumb... Well, thanks anyway :) – Daniel Dec 4 '14 at 15:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.