Seeing 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:
-
How to calculate the number of working days in a month, in other words discount Saturdays and Sundays from a month's total number of days. It sounds pre ...
-
Picked this cool little PHP function to calculate and return the last day of a month for any year off the always informative lutrov interactive website the ...
-
A big headache for developers, particularly when it comes to database-driven applications, is the differing date formats across country borders, a classic e ...
-
If you are working on an Ubuntu server installation that comes in the command line only variation, you might at any point in time want to see just what exac ...
-
Annoyingly, my JavaScript datePicker on one of our projects was throwing up peculiar values at certain page load times and to be honest, it simply didn't ma ...