Never have my feelings towards JavaScript been summed up better than by this single photo:
Case and point, I was attempting to make use of JavaScriptâs getDay()
 to obtain a numerical value for the day of the week.
Hereâs what I get using the command line JSC:
>>> (new Date()).getDay(); // Right now it's a Sunday
0
OK, so my assumption had been that JavaScript would count Monday as the first day of the week, not Sunday, so I was expecting 6
 as the returned value. According to the ISOâ8601 standard, it seems it wasnât an unreasonable assumption either.
Itâs not the end of the world. In my database, Iâd created a field with an enumeration such that monday
 was the first day of the week, etc. The obvious approach is to apply some basic arithmetic by deducting 1
 from the value returned by getDay()
 and applying a modulus function against the value to ensure that Sundayâs value of -1
 flips over to become 6
:
>>> ((new Date()).getDay() - 1) % 7; // Maths to the rescue!
-1
Hang onâŚÂ thatâs not right at all.
Whatâs happening? Well, it seems JavaScript has a bug in its implementation of the modulus function which means it doesnât really deal with negative numbers. My next thought was that we could just add 7 to the value before applying the modulus function:
>>> ((new Date()).getDay() - 1 + 7) % 7; // Yuk! I couldn't think of a better approach.
6
It works, but itâs not particularly elegant, is it? My subsequent thought was that I was being obtuse, that there had to be a nicer way of doing this. But it seems that the above approach is endemic of the workarounds used by others, for example this blogger recommends a slightly different approach which is along the same lines.
Letâs just sanity check this approach before signing off:
>>> ((new Date('2017/06/04')).getDay() - 1 + 7) % 7; // Sunday (6th day of week when counting from 0)
6
>>> ((new Date('2017/06/05')).getDay() - 1 + 7) % 7; // Monday (0th day of week when counting from 0)
0
>>> ((new Date('2017/06/06')).getDay() - 1 + 7) % 7; // Tuesday (1st day of week when counting from 0)
1
>>> ((new Date('2017/06/10')).getDay() - 1 + 7) % 7; // Saturday (5th day of week when counting from 0)
5
So, to recap, I had to account for two unexpected things here:
- JavaScript counterintuitively treats Sunday as the first day of the week.
- JavaScriptâs modulus function doesnât handle negative input values gracefully.
Iâd love to hear if thereâs a better workaround for the modulus issue, or what the original reasons were for implementing Sunday as the first day of the week (Iâve not investigated how other languages handle this⌠it could well be common), so please leave a comment!