Count the Number of Days in a Month with PHP

There are several options to calculate the number of days in PHP:

  • we can use the build-in cal_days_in_month function,
  • use the date function (with the timestamp for the current month),
  • use the DateTime class (starting from PHP 5)

Let's start with the date function. To get the number of days, we use the t-option for the format parameter. We provide also the timestamp for the month by calling the mktime function:

$month = 1; // number 1 - 12
$year = 2022;
$days_in_month = date("t", mktime(0, 0, 0, $month, 1, $year));
echo $days_in_month; // 31

Or if you just want the number of days in the current month:

$days_in_month = date("t");

Other option is to use build-in PHP function cal_days_in_month:

$month = 1; // number 1 - 12
$year = 2022;
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);
echo $days_in_month; // 31

And now we use the DateTime class and the format method:

$date = new DateTime("2022-01-01");
echo $date->format("t"); // 31

Please note that the format method returns a string and not a number.