Get first day of week in PHP?

Solution 1:

Here is what I am using...

$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));

$day contains a number from 0 to 6 representing the day of the week (Sunday = 0, Monday = 1, etc.).
$week_start contains the date for Sunday of the current week as mm-dd-yyyy.
$week_end contains the date for the Saturday of the current week as mm-dd-yyyy.

Solution 2:

Very simple to use strtotime function:

echo date("Y-m-d", strtotime('monday this week')), "\n";   

echo date("Y-m-d", strtotime('sunday this week')), "\n";

It differs a bit across PHP versions:

Output for 5.3.0 - 5.6.6, php7@20140507 - 20150301, hhvm-3.3.1 - 3.5.1

2015-03-16
2015-03-22

Output for 4.3.5 - 5.2.17

2015-03-23
2015-03-22

Output for 4.3.0 - 4.3.4

2015-03-30
2015-03-29

Comparing at Edge-Cases

Relative descriptions like this week have their own context. The following shows the output for this week monday and sunday when it's a monday or a sunday:

$date = '2015-03-16'; // monday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";   
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";

$date = '2015-03-22'; // sunday
echo date("Y-m-d", strtotime('monday this week', strtotime($date))), "\n";   
echo date("Y-m-d", strtotime('sunday this week', strtotime($date))), "\n";

Againt it differs a bit across PHP versions:

Output for 5.3.0 - 5.6.6, php7@20140507 - 20150301, hhvm-3.3.1 - 3.5.1

2015-03-16
2015-03-22
2015-03-23
2015-03-29

Output for 4.3.5 - 5.0.5, 5.2.0 - 5.2.17

2015-03-16
2015-03-22
2015-03-23
2015-03-22

Output for 5.1.0 - 5.1.6

2015-03-23
2015-03-22
2015-03-23
2015-03-29

Output for 4.3.0 - 4.3.4

2015-03-23
2015-03-29
2015-03-30
2015-03-29

Solution 3:

strtotime('this week', time());

Replace time(). Next sunday/last monday methods won't work when the current day is sunday/monday.

Solution 4:

Keep it simple :

<?php    
$dateTime = new \DateTime('2020-04-01');
$monday = clone $dateTime->modify(('Sunday' == $dateTime->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dateTime->modify('Sunday this week');    
?>

Source : PHP manual

NB: as some user commented the $dateTime value will be modified.