5

Possible Duplicate:
Get first day of week in PHP?

When a date is given I should get the date of Monday of that week.

When 2012-08-08 is given it should return 2012-08-06.

Community
  • 1
  • 1
Yasitha
  • 2,233
  • 4
  • 24
  • 36

2 Answers2

11
function last_monday($date) {
    if (!is_numeric($date))
        $date = strtotime($date);
    if (date('w', $date) == 1)
        return $date;
    else
        return strtotime(
            'last monday',
             $date
        );
}

echo date('m/d/y', last_monday('8/14/2012')); // 8/13/2012 (tuesday gives us the previous monday)
echo date('m/d/y', last_monday('8/13/2012')); // 8/13/2012 (monday throws back that day)
echo date('m/d/y', last_monday('8/12/2012')); // 8/06/2012 (sunday goes to previous week)

try it: http://codepad.org/rDAI4Scr

... or a variation that has sunday return the following day (monday) rather than the previous week, simply add a line:

 elseif (date('w', $date) == 0)
    return strtotime(
        'next monday',
         $date
    );

try it: http://codepad.org/S2NhrU2Z

You can pass it a timestamp or a string, you'll get back a timestamp

Documentation

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
3

You can make a timestamp easily with the strtotime function - it accepts both a phrase like "last monday" as well as a secondary parameter which is a timestamp that you can make easily from the date you have using mktime (note that the inputs for a particular date are Hour,Minute,Second,Month,Day,Year).

<?php
    $monday=strtotime("monday this week", mktime(0,0,0, 8, 8, 2012));
    echo date("Y-m-d",$monday);
    // Output: 2012-08-06
?>

Edit changed "last monday" in strtotime to "monday this week" and it now works perfectly.

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
Fluffeh
  • 33,228
  • 16
  • 67
  • 80