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
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
>>> ((new Date()).getDay() - 1) % 7; // Maths to the rescue! -1
Hang on… that’s not right at all.
>>> ((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:
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!