PHP: How to get the last day of a month

Assume you have year, and month, now you want to get the last date of the month for that particular year. How to do that?

Using the function strtotime() and date() you can easily achieve the goal. Here is a small function which will accept the year, and month value, and will return you the last date of the month.

## accepts year and month
## returns thelast day of the month
function get_last_day($year, $month){

$timestamp = strtotime("$year-$month-01");
$number_of_days = date('t',$timestamp);
return $number_of_days;
}


At above function, using the strtotime() I have converted the date into timestamp, and using date() function I got the number of days of that month (which is last day of the month)

To use the function, here is an example
$year = 2024;
$month = 2;
print get_last_day($year, $month);


This will print 29 on screen, as 29 is the last day of the month of February of 2024.

Comments

Anonymous said…
Thanks for sharing your findings. In this case, you can also use the php function "cal_days_in_month" which works for most dates of interest (between the 1500s or so to some time in the future. For example:

$num = cal_days_in_month(CAL_GREGORIAN, $month, $year);

Or you could use the date and mktime functions:

$last_day = date('d', mktime(0, 0, 0, $this->month + 1, 0, $this->year));

Keep coding and sharing.