JavaScript: Calculate the Number of Days in a Month CodeUnit 02 SEP 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.

For example, to calculate the number of days in the current month:

var time=new Date();
var numberOfDays = 32 - new Date(time.getFullYear (), time.getMonth(), 32).getDate();


About Craig Lotter

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