Home / Get the number of days in a month with PHP

Get the number of days in a month with PHP

This post shows how to get the number of days in a month with PHP by specifying the year and month. This can be useful when generating a calendar application without having to manually code in the number of days each month has, and not having to worry about the number of days in February which varies on leap years.

cal_days_in_month() function

The PHP function cal_days_in_month() returns the number of days for a given month and year. Which calendar to use is also a parameter but it would be rare to use anything other than CAL_GREGORIAN.

The first example would echo the number of days in August 2009 (the month and year this post was written), which is 31:

echo cal_days_in_month(CAL_GREGORIAN, 8, 2009);

The second example loops through the years from 2000 to 2008 and echos the number of days in February for each of those years:

for($i = 2000; $i < 2009; $i++) {
    echo "$i: ", cal_days_in_month(CAL_GREGORIAN, 2, $i), "n";
}

The output from the above example is:

2000: 29
2001: 28
2002: 28
2003: 28
2004: 29
2005: 28
2006: 28
2007: 28
2008: 29

Current Month: date("t")

To get the number of days for the current month you can simply use the date() function passing in "t" as the format. This returns the number of days for the given month, and when no timestamp is passed in is the current datetime.