Skip to content

Instantly share code, notes, and snippets.

@sumonst21
Forked from stecman/monday-for-week.php
Created June 24, 2022 10:13
Show Gist options
  • Save sumonst21/9eec0f9c2cbcdf37b0bb858337feb6dc to your computer and use it in GitHub Desktop.
Save sumonst21/9eec0f9c2cbcdf37b0bb858337feb6dc to your computer and use it in GitHub Desktop.
Reliable PHP function to return Monday for week (pre-PHP 7.1)
<?php
/**
* Find the starting Monday for the given week (or for the current week if no date is passed)
*
* This is required as strtotime considers Sunday the first day of a week,
* making strtotime('Monday this week') on a Sunday return the adjacent Monday
* instead of the previous one.
*
* @param string|\DateTime|null $date
* @return \DateTime
*/
function getStartOfWeekDate($date = null)
{
if ($date instanceof \DateTime) {
$date = clone $date;
} else if (!$date) {
$date = new \DateTime();
} else {
$date = new \DateTime($date);
}
$date->setTime(0, 0, 0);
if ($date->format('N') == 1) {
// If the date is already a Monday, return it as-is
return $date;
} else {
// Otherwise, return the date of the nearest Monday in the past
// This includes Sunday in the previous week instead of it being the start of a new week
return $date->modify('last monday');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment