JavaScript: Calculate the Number of Days in Last Month and Set a Date Range for it CodeUnit 01 JUL 2011

A simple way to calculate how many days are in a month in Javascript is to leverage Javascript’s built in date overflow feature – basically if you give it an incorrect date it automatically adjusts it to the correct one by assuming that the overflow are days which need simply to be added to the given date.

So, given a month and a year, it is a simply matter of forcing a date to overflow by a certain amount and then by subtracting the result from that overflow amount to learn how many days are in that month.

Thus by setting the start marker to one month back in time, we can easily learn how many days were in the last month, making it a snap to provide a quick last month range pick for a calendar control.

var time=new Date();
//force the date object to last month
var currentMonth = time.getMonth();
time.setMonth(time.getMonth()-1);
while(currentMonth == time.getMonth()){
    time.setMonth(time.getMonth()-1);
}
//get the last day of last month
var lastDay = 32 - new Date(time.getFullYear (), time.getMonth(), 32).getDate();
//if we were setting a last month range for a calendar control
var monthstart = new Date(time.getFullYear (),time.getMonth(),1);
var monthend = new Date(time.getFullYear (),time.getMonth(),lastDay);

Nifty.

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.