Last active
October 1, 2024 13:26
-
-
Save stecman/0203410aa4da0ef01ea9 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
Looks like this was tried to be fixed by v5.6.23 and v7.0.8, but only properly fixed by v7.0.17.