Javascript: Number of Days in a Month Function

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:

$(“#viewthismonth”).click(function()
{
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)));
alert(monthend);
});

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?

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials. Bookmark the permalink.
    blog comments powered by Disqus