JavaScript Strikes Again!

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

(source: http://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!

Leave a comment

Website Powered by WordPress.com.

Up ↑