-
-
Save sumonst21/9eec0f9c2cbcdf37b0bb858337feb6dc to your computer and use it in GitHub Desktop.
Reliable PHP function to return Monday for week (pre-PHP 7.1)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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