Days in Month

While the JavaScript Date object doesn't provide a method for obtaining the number of days in the current month, we can add such a method ourselves quite simply by taking advantage of the fact that a date object treats day zero of any month as being the last day of the preceding month. To return the number of days in the current month all we need to do is to add one to the month, set the day of the month to zero and then return the day of the month.

Date.prototype.daysInMonth = function() {
var dd = new Date(this);
return dd.getDate();

Looking at that code you might think that it would be simpler to just set up an array containing the number of days in each month and do a lookup using the current month value but that is complicated by the fact that February doesn't always have the same number of days. If you were to perform the array lookup you'd still need to add tests for each of the rules for determining if you need to add the extra leap day to February. The above version of the code is shorter than the resultant code testing just the first two of the three leap year rules because it makes use of the leap year rules built into the JavaScript date object itself.

If you create a simple function that accepts the year and month as parameters rather than extending your Date objects then you can make the code for determining the number of days in the current month even shorter.

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


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow