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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With