Last active
June 24, 2022 10:13
-
-
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 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
Thanks @abePdIta - it looks like the interpretation of "monday this week" may have been properly fixed from about PHP 7.1 onwards. This snippet was written in 2014 against PHP 5.5 when this was definitely a problem.
Your version, with
2020-12-06
as an input (tool):The original, with
2020-12-06
as an input (tool):I couldn't pin down one single patch that addresses this issue, but good to know that the "monday this week" behaviour is consistent in actively supported versions of PHP 👍
Regarding
setTime()
, the week technically starts at midnight on Monday. The original code leveraged this to test for equality between outputDateTime
objects, but you're correct that it's not strictly required.