It's fairly easy given the powerful date/time functions in PHP:
$now = new \DateTime('now');
# "1" means "Monday", you could improve this by detecting localized settings
$daysToMove = (int)($now->format('N')) - 1; //
# How many days to subtract?
if ($daysToMove){
$now->sub(new \DateInterval('P' . $daysToMove . 'D'));
}
echo "Start of the week: " . $now->format('Y-m-d');
Simple explanation:
- you calculate current day of the week. This value can be in range
1..7
. - Since, Monday is
1
, subtract1
from calculated number. - If resulting number of greater that
0
(meaning "today is not Monday"), createDateInterval
and subtract it from current date.
You can find more about DateTime
and DateInterval
classes: here. Look for Examples
section...
PHP date()
: date
PHP DateTime
(OOP variant): DateTime