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.
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 LondonWestern Europe time.
1