To get the last day of the month for a given date using DateTime in PHP, you can follow these steps:
format
method on the DateTime object to extract the month and year in the 'Y-m' format.modify
method on the second DateTime object to set the date to the first day of the next month.modify
method again, subtracting 1 day from the date to get the last day of the current month.format
method to extract the day of the last day of the month.Here is an example code snippet demonstrating this:
$dateString = '2022-01-15'; // Example given date
// Create a DateTime object with the given date
$date = new DateTime($dateString);
// Extract month and year in 'Y-m' format and create the first day of the month date
$firstDayOfMonth = $date->format('Y-m') . '-01';
// Create a new DateTime object for the first day of the month
$firstDayObj = new DateTime($firstDayOfMonth);
// Modify the date to set it to the first day of the next month
$firstDayObj->modify('+1 month');
// Subtract 1 day from the date to get the last day of the current month
$lastDayObj = $firstDayObj->modify('-1 day');
// Extract the day of the last day of the month
$lastDayOfMonth = $lastDayObj->format('d');
echo "Last day of the month: " . $lastDayOfMonth;
In this example, the output will be:
Last day of the month: 31
Note: This method assumes that the given date is a valid date in the Gregorian calendar.