Javascript: Number of Days in a Month Function CodeUnit 18 MAR 2009

Coffee CupSeeing as I’m currently so busy implementing datepickers and such at work at the moment, here’s a nifty little bit jQuery/Javascript code that I whipped up to work out the last day of a month:

var time=new Date();
var dd = new Date(time.getFullYear (), time.getMonth(), 32);
var dd2 = new Date(time.getFullYear (), time.getMonth() + 1, 1);
//Set 1 day in milliseconds
var one_day=1000*60*60*24;
var monthend = new Date(time.getFullYear (),time.getMonth(),(32 – ((Math.ceil((dd.getTime()-dd2.getTime())/(one_day))) + 1)));

The trick lies in Javascript’s Date construct automatically handling date overflows by simply returning the correct date after automatically shifting the invalid inputted date onwards as necessary.

This example works out the number of days in the current month, so to start off we create a Date variable and pass to it the current year, the current month and then an invalid value of 32 as the day part.

This then returns a valid date that has been shifted into the new month, meaning that should we be testing February, the date returned would in fact be 4 March 2009. We then create a second date variable for the first day of the next month against which we are testing, meaning that we would be creating a date that is equal to the 1 March 2009. Then a simple subtraction between the two dates (using the Date.getTime functionality to return a usable integer-based value for the two dates) and a division to force it back into a day count will provide us with the number of days we need to subtract from 32, giving us in return the exact last day of the current month that we were checking for.

Nifty, eh?

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.