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!