How to get the last day of the month for a given date using DateTime in PHP?

To get the last day of the month for a given date using DateTime in PHP, you can follow these steps:

  1. Create a new DateTime object with the given date.
  2. Use the format method on the DateTime object to extract the month and year in the 'Y-m' format.
  3. Concatenate the month and year with '-01' to create a new date string representing the first day of the month.
  4. Create another DateTime object with the new date string.
  5. Use the modify method on the second DateTime object to set the date to the first day of the next month.
  6. Use the modify method again, subtracting 1 day from the date to get the last day of the current month.
  7. Use the 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.