Last Day of the Month

Getting the last day of any particular month of the year would be a simple array lookup if it were not for February and leap years. If we were to create a function to do the array lookup of the last day of the month for all months apart from February and then apply the three leap year rules then most of the function would be code to apply those leap year rules. The shortest version of the code would look like the following with the leap year rules being applied out of order (the third leap year rule which first takes effect in 4882 comes first as that is the rule that covers when there is a leap year not exactly divisible by four).

daysInMonth = function(month,year) {
var m = [31,28,31,30,31,30,31,31,30,31,30,31];
if (2 !== month) return m[month - 1];
if (0 === (year-1582)%3300) return 29;
if (0 !== year%4) return m[1];
if (0 === year%100 && 0 !== year%400) return m[1];
return 29;

Even discarding that third leap year rule (given that for most situations we are unlikely to be dealing with dates that far in the future) we only save one line of code.

There is a completely different approach that we can take in JavaScript that involves a lot less code. We can make use of the way that the built in Date object works when it is supplied with values outside of the normal range. To set a date object to the last day of a month all we need to do is to create a date object set to day zero of the following month. The zeroth day of a month is always considered to be the last day of the preceding month. Our code is made even simpler due to the fact that JavaScript treats the months as going from 0 to 11 instead of 1 to 12 (since it makes array lookups easier and most of the time you want to display the name of a month rather than its number). So simply passing the real month number (1 through 12) without subtracting one from it automatically gives us the following month (with 12 giving us January of the following year).

Once we have set a date object that way simply retrieving the day of the month from it gives us the last day of the month.

daysInMonth = function(month,year) {
var dd = new Date(year, month, 0);
return dd.getDate();

Internally the date object needs to take into account the leap year processing and probably omits rule three (since most computer programs currently do) but it can of course be added into the JavaScript Date object itself long before it becomes relevant. The processing performed within JavaScript itself to provide the result will be faster than where we code the leap year rules for ourself. So this code is both shorter and faster than the first version as well as making it unnecessary to know how to test for any of the leap year rules.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow