143

Given a date MM-dd-yyyy format, can someone help me get the first day of the week?

robjmills
  • 18,438
  • 15
  • 77
  • 121
Iggy Ma
  • 1,439
  • 2
  • 10
  • 3

39 Answers39

168

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.

JadedCore
  • 1,993
  • 1
  • 13
  • 20
  • 1
    but, it means the start and the end of 'this week', right? – Oki Erie Rinaldi Aug 07 '15 at 06:59
  • what if the week number is given? and i want it returns the start and the end date of that week. – Oki Erie Rinaldi Aug 07 '15 at 07:00
  • 1
    @OkiErieRinaldi You should probably open a new question in order to receive the proper attention. – JadedCore Aug 11 '15 at 12:39
  • Don't worry,, i got it @JadedCore! – Oki Erie Rinaldi Aug 12 '15 at 01:34
  • I'm not sure why the other one is higher. It doesn't work, but this one does! https://3v4l.org/q6kKY – Jason Mar 23 '16 at 23:30
  • I think this answer needs to pass the first `date` function and the `strtotime`function the timestamp of the given date **MM-dd-yyyy**. Otherwise this would just compute the Monday of the current week. – Adam Sep 20 '17 at 10:02
  • If you want to figure this out for an arbitrary date that you can pass in (`$date`), you can do it like `$time = strtotime($date); $day = date('w', $time); $first_of_week = date('m-d-Y', strtotime('-'.$day.' days', $time));` – WOUNDEDStevenJones Jun 18 '18 at 22:33
  • in this case week is in US format (Sun is start), for Europeans needs to be converted: $day = !$day ? 6 : --$day; – 8ctopus Jul 15 '20 at 11:13
  • The following gives Monday for a given date: date('Y-m-d', strtotime('-'.(date('w', strtotime($date)) - 1).' days', strtotime($date))) – yenren Oct 08 '20 at 10:45
  • Thanks, this code works for me. – Javed Iqbal Jan 13 '22 at 14:54
  • 1
    @8ctopus `date("N")` can also be used. According to https://www.php.net/manual/en/datetime.format.php `N` is the "ISO 8601 numeric representation of the day of the week". It just needs to be decremented to be used in this code. – Cave Johnson Aug 25 '23 at 05:52
94

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
hakre
  • 193,403
  • 52
  • 435
  • 836
Raja Rama Mohan Thavalam
  • 8,131
  • 2
  • 31
  • 30
  • why is this not working for date 2016-06-05, its giving next weeks dates. –  Jun 26 '16 at 12:02
  • 1
    Thanks for this, i just modified this code so i can pass an optional date parameter $dt = $custom_date ? strtotime($custom_date) : time(); $monday = date("Y-m-d", strtotime('monday this week', $dt)); $sunday = date("Y-m-d", strtotime('sunday this week', $dt)); – Ron Michael Aug 04 '19 at 02:55
70
strtotime('this week', time());

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

laurentb
  • 1,075
  • 8
  • 6
  • 59
    `$monday = strtotime('last monday', strtotime('tomorrow'));` – Lewis Buckley Jul 30 '13 at 15:04
  • `this week` does not work if you need to have always previous start of week, but @LewisBuckley’s comment does it. – Smar Dec 10 '13 at 14:11
  • Second argument `time()` is optionnal if you want to specify today. – Ifnot Jan 07 '14 at 12:27
  • did not work for me, I had to se slightly different syntax for YTD, MTD, WTD. – Ron Apr 08 '14 at 00:14
  • 8
    This answer produces inconsistent results, depending on the PHP version used: http://3v4l.org/Z3k4E @LewisBuckley's solution is consistent for all versions: http://3v4l.org/Eeh9c – Chris Baker Jun 25 '14 at 14:45
  • @LewisBuckley's answer works great but it can be combined into a single strtotime: `strtotime('last Monday tomorrow', $intTimestamp)` – Eugene C May 07 '15 at 20:00
56

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.

job3dot5
  • 862
  • 7
  • 7
  • edit: typo or some unknown syntax ? where does the \ come from ? `$dateTime = new \DateTime('2012-05-14');` – Sliq May 14 '12 at 13:56
  • 2
    I'm doing this avoid any conflict with a possible autoloaded object of your application. That's like absolute path or relative path. – job3dot5 May 14 '12 at 14:53
  • 9
    @Panique - the "unknown syntax" is PHP 5.3's Namespace syntax. Namespacing allows you to prefix a class with a namespace followed by a backslash. Here he's using it without a namespace in order to specify the core `DateTime` class, which means the code will work even if you have another class called `DateTime` in the current namespace. – Spudley May 14 '12 at 18:41
  • Is the day name always in English? – Marwelln Aug 27 '16 at 17:08
  • Cheers, best answer. Mostly because the autor is asking for a `DateTime`solution while the most answers does not provide a `DateTime` solution. – lin Nov 15 '16 at 09:36
  • As the author looking for a DateTime solution, this should be the best answer ! – GuiPab Jan 30 '19 at 20:26
  • 2
    Clone part is not working correctly. You should clone first then make operation on clone if you need original one. – Farid Movsumov Sep 09 '19 at 13:48
25
$givenday = date("w", mktime(0, 0, 0, MM, dd, yyyy));

This gives you the day of the week of the given date itself where 0 = Sunday and 6 = Saturday. From there you can simply calculate backwards to the day you want.

James Skidmore
  • 49,340
  • 32
  • 108
  • 136
Yuvalik
  • 425
  • 3
  • 3
  • 6
    This answer returns whether a given date is sunday or monday etc. But, the questioner has asked for the date of the sunday of the week of the given date as mentioned in his comment on the original question. – Rakib Aug 26 '12 at 16:40
21

This question needs a good DateTime answer:-

function firstDayOfWeek($date)
{
    $day = DateTime::createFromFormat('m-d-Y', $date);
    $day->setISODate((int)$day->format('o'), (int)$day->format('W'), 1);
    return $day->format('m-d-Y');
}

var_dump(firstDayOfWeek('06-13-2013'));

Output:-

string '06-10-2013' (length=10)

This will deal with year boundaries and leap years.

vascowhite
  • 18,120
  • 9
  • 61
  • 77
20

EDIT: the below link is no longer running on the version of PHP stated. It is running on PHP 5.6 which improves the reliability of strtotime, but isn't perfect! The results in the table are live results from PHP 5.6.

For what it's worth, here is a breakdown of the wonky behavior of strtotime when determining a consistent frame of reference:

http://gamereplays.org/reference/strtotime.php

Basically only these strings will reliably give you the same date, no matter what day of the week you're currently on when you call them:

strtotime("next monday");
strtotime("this sunday");
strtotime("last sunday"); 
AgmLauncher
  • 7,070
  • 8
  • 41
  • 67
  • The article also gave some specific code to use: $start_of_week = strtotime("next monday - 1 week"); // Will return Monday of the current week starting at 00:00:00" $end_of_week = strtotime("next monday - 1 second"); // Will return Sunday of the current week ending at 23:59:59" – Scott M. Stolz Apr 20 '19 at 13:18
12

Assuming Monday as the first day of the week, this works:

echo date("M-d-y", strtotime('last monday', strtotime('next week', time())));
shasi kanth
  • 6,987
  • 24
  • 106
  • 158
11

The following code should work with any custom date, just uses the desired date format.

$custom_date = strtotime( date('d-m-Y', strtotime('31-07-2012')) ); 
$week_start = date('d-m-Y', strtotime('this week last monday', $custom_date));
$week_end = date('d-m-Y', strtotime('this week next sunday', $custom_date));
echo '<br>Start: '. $week_start;
echo '<br>End: '. $week_end;

I tested the code with PHP 5.2.17 Results:

Start: 30-07-2012
End: 05-08-2012
Malagana
  • 135
  • 1
  • 3
  • 1
    Worth noting that this will always return the previous Monday, so if $custom_date is a Monday, it will return the date of Monday one week earlier. – Hill79 Feb 05 '13 at 14:08
  • 2
    Does not work properly, today is sunday, results are: Start: 09-09-2013 End: 22-09-2013 – user2019515 Sep 15 '13 at 21:49
9

How about this?

$first_day_of_week = date('m-d-Y', strtotime('Last Monday', time()));
$last_day_of_week = date('m-d-Y', strtotime('Next Sunday', time()));
birkof
  • 634
  • 1
  • 6
  • 14
8

This is what I am using to get the first and last day of the week from any date. In this case, monday is the first day of the week...

$date = date('Y-m-d') // you can put any date you want
$nbDay = date('N', strtotime($date));
$monday = new DateTime($date);
$sunday = new DateTime($date);
$monday->modify('-'.($nbDay-1).' days');
$sunday->modify('+'.(7-$nbDay).' days');
ThEBiShOp
  • 506
  • 8
  • 23
6

Here I am considering Sunday as first & Saturday as last day of the week.

$m = strtotime('06-08-2012');  
$today =   date('l', $m);  
$custom_date = strtotime( date('d-m-Y', $m) );   
if ($today == 'Sunday') {  
   $week_start = date("d-m-Y", $m);  
} else {  
  $week_start = date('d-m-Y', strtotime('this week last sunday', $custom_date));  
}  

if ($today == 'Saturday') {  
  $week_end = date("d-m-Y", $m);
} else {  
  $week_end = date('d-m-Y', strtotime('this week next saturday', $custom_date));  
}
echo '<br>Start: '. $week_start;  
echo '<br>End: '. $week_end;  

Output :

Start: 05-08-2012
End: 11-08-2012

Irshad Sheikh
  • 61
  • 1
  • 1
5

Just use date($format, strtotime($date,' LAST SUNDAY + 1 DAY'));

Undo
  • 25,519
  • 37
  • 106
  • 129
Kondziutek
  • 143
  • 1
  • 6
5

How about this?

$day_of_week = date('N', strtotime($string_date));
$week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
$week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));
4

Try this:

function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
    $wk_ts  = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
    $mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
    return date($format, $mon_ts);
}

$sStartDate = week_start_date($week_number, $year);
$sEndDate   = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));

(from this forum thread)

James Skidmore
  • 49,340
  • 32
  • 108
  • 136
4

This is the shortest and most readable solution I found:

    <?php
    $weekstart = strtotime('monday this week');
    $weekstop = strtotime('sunday this week 23:59:59');
    //echo date('d.m.Y H:i:s', $weekstart) .' - '. date('d.m.Y H:i:s', $weekstop);
    ?>

strtotime is faster than new DateTime()->getTimestamp().

dipser
  • 442
  • 3
  • 5
4
$string_date = '2019-07-31';
echo $day_of_week = date('N', strtotime($string_date));
echo $week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
echo $week_last_day = date('Y-m-d', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));
3
$monday = date('d-m-Y',strtotime('last monday',strtotime('next monday',strtotime($date))));

You have to get next monday first then get the 'last monday' of next monday. So if the given date is monday it will return the same date not last week monday.

Fedy Venom
  • 399
  • 4
  • 11
2

Given PHP version pre 5.3 following function gives you a first day of the week of given date (in this case - Sunday, 2013-02-03):

<?php
  function startOfWeek($aDate){
    $d=strtotime($aDate);
    return strtotime(date('Y-m-d',$d).' - '.date("w",$d).' days');
  }

  echo(date('Y-m-d',startOfWeek("2013-02-07")).'
');
?>
David Jashi
  • 4,490
  • 1
  • 21
  • 26
2
$today_day = date('D'); //Or add your own date
$start_of_week = date('Ymd');
$end_of_week = date('Ymd');

if($today_day != "Mon")
    $start_of_week = date('Ymd', strtotime("last monday"));

if($today_day != "Sun")
                    $end_of_week = date('Ymd', strtotime("next sunday"));
user195257
  • 3,186
  • 5
  • 36
  • 49
2

If you want Monday as the start of your week, do this:

$date = '2015-10-12';
$day = date('N', strtotime($date));
$week_start = date('Y-m-d', strtotime('-'.($day-1).' days', strtotime($date)));
$week_end = date('Y-m-d', strtotime('+'.(7-$day).' days', strtotime($date)));
Henry Weber
  • 621
  • 6
  • 10
  • What makes this preferable to [this answer](http://stackoverflow.com/a/31525270/1677912), or [this answer](http://stackoverflow.com/a/27420417/1677912)? Seems to me there are more than enough options in the 30 other answers... – Mogsdad Aug 14 '15 at 01:10
  • Thx. this is simple solution and it works like a charm. – Oleg Popov Aug 15 '16 at 11:49
2

A smart way of doing this is to let PHP handle timezone differences and Daylight Savings Time (DST). Let me show you how to do this.

This function will generate all days from Monday until Friday, inclusive (handy for generating work week days):

class DateTimeUtilities {
    public static function getPeriodFromMondayUntilFriday($offset = 'now') {
        $now = new \DateTimeImmutable($offset, new \DateTimeZone('UTC'));
        $today = $now->setTime(0, 0, 1);

        $daysFromMonday = $today->format('N') - 1;

        $monday = $today->sub(new \DateInterval(sprintf('P%dD', $daysFromMonday)));
        $saturday = $monday->add(new \DateInterval('P5D'));

        return new \DatePeriod($monday, new \DateInterval('P1D'), $saturday);
    }
}

foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday() as $day) {
    print $day->format('c');
    print PHP_EOL;
}

This will return datetimes Monday-Friday for current week. To do the same for an arbitrary date, pass a date as a parameter to DateTimeUtilities ::getPeriodFromMondayUntilFriday, thus:

foreach (DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00') as $day) {
    print $day->format('c');
    print PHP_EOL;
}

//prints 
//2017-01-02T00:00:01+00:00
//2017-01-03T00:00:01+00:00
//2017-01-04T00:00:01+00:00
//2017-01-05T00:00:01+00:00
//2017-01-06T00:00:01+00:00

Only interested in Monday, as the OP asked?

$monday = DateTimeUtilities::getPeriodFromMondayUntilFriday('2017-01-02T15:05:21+00:00')->getStartDate()->format('c');
print $monday;
// prints
//2017-01-02T00:00:01+00:00
The Onin
  • 5,068
  • 2
  • 38
  • 55
1

I've come against this question a few times and always surprised the date functions don't make this easier or clearer. Here's my solution for PHP5 that uses the DateTime class:

/**
 * @param DateTime $date A given date
 * @param int $firstDay 0-6, Sun-Sat respectively
 * @return DateTime
 */
function getFirstDayOfWeek(DateTime $date, $firstDay = 0) {
    $offset = 7 - $firstDay;
    $ret = clone $date;
    $ret->modify(-(($date->format('w') + $offset) % 7) . 'days');
    return $ret;
}

Necessary to clone to avoid altering the original date.

contrebis
  • 1,287
  • 1
  • 11
  • 20
1

You parse the date using strptime() and use date() on the result:

date('N', strptime('%m-%d-%g', $dateString));
soulmerge
  • 73,842
  • 19
  • 118
  • 155
1
<?php
/* PHP 5.3.0 */

date_default_timezone_set('America/Denver'); //Set apprpriate timezone
$start_date = strtotime('2009-12-15'); //Set start date

//Today's date if $start_date is a Sunday, otherwise date of previous Sunday
$today_or_previous_sunday = mktime(0, 0, 0, date('m', $start_date), date('d', $start_date), date('Y', $start_date)) - ((date("w", $start_date) ==0) ? 0 : (86400 * date("w", $start_date)));

//prints 12-13-2009 (month-day-year)
echo date('m-d-Y', $today_or_previous_sunday);

?>

(Note: MM, dd and yyyy in the Question are not standard php date format syntax - I can't be sure what is meant, so I set the $start_date with ISO year-month-day)

micahwittman
  • 12,356
  • 2
  • 32
  • 37
1

Another way to do it....

$year = '2014';
$month = '02';
$day = '26';

$date = DateTime::createFromFormat('Y-m-d H:i:s', $year . '-' . $month . '-' . $day . '00:00:00');
$day = date('w', $date->getTimestamp());

// 0=Sunday 6=Saturday
if($day!=0){

   $newdate = $date->getTimestamp() - $day * 86400;  //86400 seconds in a day

   // Look for DST change 
   if($old = date('I', $date->getTimestamp()) != $new = date('I', $newdate)){
       if($old == 0){
           $newdate -= 3600;  //3600 seconds in an hour
       } else {
           $newdate += 3600;
       }
   }

   $date->setTimestamp($newdate);
}

echo $date->format('D Y-m-d H:i:s');
1

The easiest way to get first day(Monday) of current week is:

strtotime("next Monday") - 604800;

where 604800 - is count of seconds in 1 week(60*60*24*7).

This code get next Monday and decrease it for 1 week. This code will work well in any day of week. Even if today is Monday.

Anton Popov
  • 191
  • 2
  • 5
1

I found this quite frustrating given that my timezone is Australian and that strtotime() hates UK dates.

If the current day is a Sunday, then strtotime("monday this week") will return the day after.

To overcome this:

Caution: This is only valid for Australian/UK dates

$startOfWeek = (date('l') == 'Monday') ? date('d/m/Y 00:00') : date('d/m/Y', strtotime("last monday 00:00"));
$endOfWeek = (date('l') == 'Sunday') ? date('d/m/Y 23:59:59') : date('d/m/Y', strtotime("sunday 23:59:59"));
zanderwar
  • 3,440
  • 3
  • 28
  • 46
1

Here's a one liner for the first day of last week, and the last day of last week as a DateTime object.

$firstDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 7))
                             ->setTime(0, 0, 0);
$lastDay = (new \DateTime())->modify(sprintf('-%d day', date('w') + 1))
                            ->setTime(23, 59, 59);
David Baucum
  • 2,162
  • 24
  • 25
1

Just to note that timestamp math can also be a solution. If you have in mind that 01.jan 1970 was a Thursday, then start of a week for any given date can be calculated with:

function weekStart($dts)
{   $res = $dts - ($dts+date('Z',$dts)+259200)%604800;
    return $res + 3600*(date('I',$dts)-date('I',$res));
}

It is predictable for any timestamp and php version, using date-func ('Z', 'I') only for timezone and daylight-saving offsets. And it produces same results as:

strtotime(date('Y-m-d', $dts).' - '.(date('N', $dts)-1.' days');

and with (the best and the most elegant) mentioned:

strtotime('monday this week', $dts); 
Asain Kujovic
  • 1,700
  • 13
  • 19
  • 1
    While you may find it a good property that computer systems are relatively fast calculating integer numbers, keep in mind that dates can not be calculated well with integers. Albeit the _UNIX Epoche_ is an integer number, it is already an abstraction of date or time. As with any abstraction it is leaking, often resulting in data-loss. E.g. you make the broad statement that 01.jan 1970 was a Thursday but miss the time (you mean 00:00:00, right?). That date at that time was not Thursday for all those dates. Take care. – hakre Dec 17 '22 at 10:54
  • Time is with timezones on planet Earth. Unix Epoch has abstracted time that much, there is no timezones within it. Just to name one of the abstractions in which you deem your function correct from 1970 to 2022. Another one is that if the second falls within a +1 leap-second (similar to leap-year, just with second resolution) in that 1970 to 2022 span, the math you present can't handle it (this is not your fault, I only write that as you've asked for the comment). /E: If you're looking for such data, Wikipedia has it: https://en.wikipedia.org/wiki/Leap_second – hakre Dec 17 '22 at 11:09
  • Sure, within the abstraction you can do the math. But you've lost the precision of date already. The leap-second is just the example of that. As the Unix-Epoch starts at 0 for the reference date and you don't know the leap-seconds ahead of time, it does not have them. Therefore at those leap-seconds it falls inside the whole. You find this in computer systems, that need patches to handle it properly, otherwise they have the wrong timestamp (and have no way to find out whether its true or not, they only stay correct for themselves as the rest has been abstracted away, it can only do the math). – hakre Dec 17 '22 at 11:20
  • This will be corrected after 2022 for a certain extend as there will be no more leap seconds IIRC. Not entirely sure if that was for unix-, global- or universally-corrdinated-time thought. – hakre Dec 17 '22 at 11:24
  • depends which kind of rounding, but more interesting I think is the MOD operation in this context. and you may get me wrong if you think that I'm saying that the math would be wrong. the point I've raised is just that the abstraction of a unix-timestamp is often not well enough to represent a date like "first day of week". mainly I'd say that for timezones alone (if not other calendar systems). If the precision and the speed of your calculation fits your needs, there is **nothing** wrong with that. YMMV. Normally there is no need to reinvent the wheel thought. – hakre Dec 17 '22 at 11:30
  • Yes, that's a real common off-by-one error (fix is: previous monday of tomorrow). Basically the same math, just a different numbering system. And also what you rightfully comment for the different definitions of start of week, e.g. monday is wrong here given week starts on sunday. – hakre Dec 17 '22 at 11:45
  • @hakre You were right, there was a problem with daylight-saving (and not with leapseconds). I have corrected the answer and deleted other comments. – Asain Kujovic Dec 19 '22 at 03:54
0

What about:

$date = "2013-03-18"; 
$searchRow = date("d.m.Y", strtotime('last monday',strtotime($date." + 1 day")));
echo "for date " .$date ." we get this monday: " ;echo $searchRow; echo '<br>';

Its not the best way but i tested and if i am in this week i get the correct monday, and if i am on a monday i will get that monday.

CoffeJunky
  • 1,087
  • 1
  • 12
  • 15
0

I found this solution helpful. Just subtract if it isn't monday to get the previous Monday. I am using $lower_date as the date I pulled from a query that I then need to reconcile to the previous Monday.

//set this up to go backwards until you find monday
while(date('D',strtotime($lower_date))!='Mon'){
    $lower_date = date('Y-m-d', strtotime($lower_date . ' - 1 day')); //increase the upper spec
}
sweaty
  • 369
  • 2
  • 4
  • 18
0

this one is prepared for today is monday

function lastMonday(\DateTime $date) {

    $timestamp = $date->getTimestamp();

    $monday = ( 1 == date( 'N', $timestamp ));

    if ($monday) {
        return $timestamp;
    } else {
        return strtotime( 'last monday', $timestamp );
    }
}

if you want it to get timestamp instead of DateTime change first two lines (get rid of date->getTimestamp) change them to just this

function lastMonday($timestamp) {

and if you want it to input string change first two lines to this

function lastMonday($dateString) {

    $timestamp = strtotime($dateString);
Jacek Pietal
  • 1,980
  • 1
  • 18
  • 27
0

I was searching for a solution similar to this and I finally came up with something that will return each day of the current week.

//set current timestamp
$today = time();
//calculate the number of days since Monday
$dow = date('w', $today);
  $offset = $dow - 1;
if ($offset < 0) {
  $offset = 6;
  }
//calculate timestamp for Monday and Sunday
$monday = $today - ($offset * 86400);
$tuesday = $monday + (1 * 86400);
$wednesday = $monday + (2 * 86400);
$thursday = $monday + (3 * 86400);
$friday = $monday + (4 * 86400);
$saturday = $monday + (5 * 86400);
$sunday = $monday + (6 * 86400);
//print dates for Monday and Sunday in the current week
print date("Y-m-d", $monday) . "\n";
print date("Y-m-d", $tuesday) . "\n";
print date("Y-m-d", $wednesday) . "\n";
print date("Y-m-d", $thursday) . "\n";
print date("Y-m-d", $friday) . "\n";
print date("Y-m-d", $saturday) . "\n";
print date("Y-m-d", $sunday) . "\n";

Thank you to dbunic who posted this here: http://www.redips.net/php/week-list-current-date/#comments

NotJay
  • 3,919
  • 5
  • 38
  • 62
0

I use it:

$firstDate = date( 'Y-m-d', strtotime( 'Last Monday', strtotime('-1 week') ));
$lastDate = date( 'Y-m-d', strtotime( 'First Sunday', strtotime('-1 week') ));

Hope this help you!

Narayon
  • 415
  • 3
  • 12
Nguyễn Thành Bồi
  • 2,457
  • 2
  • 14
  • 8
0

You can use Carbon library as well

$dateString = '02-21-2015'; // example in format MM-dd-yyyy
$date = Carbon::createFromFormat('m-d-Y', $dateString);
$date->hour(0)->minute(0)->second(0)->startOfWeek();
$dateString = $date->Format('m-d-Y'); // and you have got a string value "02-16-2015"
Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
0

Should work:

/**
 * Returns start of most recent Sunday.
 * 
 * @param null|int $timestamp
 * @return int
 */
public static function StartOfWeek($timestamp = null) {
    if($timestamp === null) $timestamp = time();
    $dow = idate('w', $timestamp); // Sunday = 0, Monday = 1, etc.
    return mktime(0, 0, 0, idate('m', $timestamp), idate('d', $timestamp) - $dow, idate('Y', $timestamp));
}

Input and output are unix timestamps. Use date to format.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
0

In order to have the simplest code and have weeks starting on monday, I used this method:

$day = (date('w')+6)%7; //transform week start from sunday to monday
$time = strtotime('-'.$day.' days');
Poupoudoum
  • 31
  • 4
-3

just simply oneline answer ;)

$mondayThisWeek = new Date($date . 'this week monday');
FiliusBonacci
  • 104
  • 1
  • 7