1. Technology
Send to a Friend via Email

Last Day of the Month

Join the Discussion

Questions? Comments?

There are various times when you are doing date manipulations and validations where you need to know how many days that there are in a specific month. There are also a variety of different ways that you can determine how many days that the month has. Some of these involve a fair amount of code while others involve almost no code at all. Unfortunately some of the shorter ways to do it don't work on all browsers.

Let's start by looking at an example of the long way of obtaining the answer we want.

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

As you can see the code is mostly concerned with working out whether or not February is or isn't a leap year (and it doesn't even check the third of the leap year rules which fortunately doesn't affect things until the 4800s).

Next we'll look at a short way that I have seen some people use in their Javascript.

function daysInMonth(month,year) {
var ds = String(monthNum+1)+'/0/'+String(yearNum);
var dd = new Date(ds);
return dd.getDate();
}

This code is much shorter than our first example and it works perfectly in some browsers. Unfortunately not all browsers process strings passed into the date constructor the same way. Internet Explorer and Firefox will treat day zero of next month as the last day of the current month and will therefore return the correct number of days so this code appears to work. Unfortunately not all browsers interpret the zero in this way. Opera for example considers a zero to represent the current day of the month and so the function will return today's date rather than the number of days in the requested month.

We can easily fix this and make our code even shorted by passing the year, month, and day into the date constructor as numbers instead of as a US date format string. This format expects month numbers between 0 and 11 instead of 1 and 12 so we don't need to add 1 to get next month as our month field is already one greater.

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

As far as I am aware, all of the different browsers will process this code correctly and return the same results as they did with the first of our daysInMonth functions above. Of course if you want to be certain that the correct result is returned and don't want to rely on browsers correct interpretation of month and day numbers outside of the usual range then you can always subsitute the first version. Also if you actually code it as a function like this it makes it straightforward to substitute one version of the code for another ar any time.

©2014 About.com. All rights reserved.