šŸ˜– JavaScript Strikes Again!

Never have my feelings towards JavaScript been summed up better than by this single photo:

Source:Ā www.shlomifish.org/open-source/anti/javascript

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!