Skip to content

Instantly share code, notes, and snippets.

@ngekoding
Created December 14, 2023 03:20
Show Gist options
  • Save ngekoding/8a36e03d0e5776943c33b9a4ab4b5cc1 to your computer and use it in GitHub Desktop.
Save ngekoding/8a36e03d0e5776943c33b9a4ab4b5cc1 to your computer and use it in GitHub Desktop.
Gets the last Sunday of the month for a given date
<?php
/**
* Gets the last Sunday of the month for a given date.
*
* @param string $dateString The input date in 'Y-m-d' format.
* @return string The last Sunday of the month in 'Y-m-d' format.
*/
function getLastSunday($dateString)
{
$date = new DateTime($dateString);
// Set the date to the last day of the current month
$date->modify('last day of this month');
// Get the day of the week for the last day of the month (0 = Sunday, 1 = Monday, ..., 6 = Saturday)
$dayOfWeek = $date->format('w');
// If the last day of the month is not already a Sunday, modify the date to be the last Sunday
if ($dayOfWeek != 0) {
$date->modify('last sunday');
}
return $date->format('Y-m-d');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment