Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a date is given how to get the date of Monday of that week in php [duplicate]

Tags:

date

php

datetime

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.

like image 912
Yasitha Avatar asked Dec 15 '22 21:12

Yasitha


2 Answers

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

  • strtotime - http://php.net/manual/en/function.strtotime.php
  • date - http://php.net/manual/en/function.date.php
like image 188
Chris Baker Avatar answered Apr 27 '23 11:04

Chris Baker


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.

like image 43
Fluffeh Avatar answered Apr 27 '23 10:04

Fluffeh