I want to use strtotime(\"last Monday\")
.
The thing is, if today IS MONDAY, what does it return? It seems to be returning the date for the monday of la
If today is Monday, strtotime("last Monday") will return a date 7 days in the past. Why don't you just check if today is Monday and if yes, return today's date and if not, return last week?
That would be a foolproof way of doing this.
if (date('N', time()) == 1) return date('Y-m-d');
else return date('Y-m-d', strtotime('last Monday'));
http://us2.php.net/manual/en/function.date.php
$monday = strtotime('Monday last week');
$sunday = strtotime('+6 days', $monday);
As it was correctly outlined in the previous answer, this trick works, but also had caveats prior to PHP 5.6.22
, PHP 7.0.7
and PHP 7.1-dev
:
strtotime('last monday', strtotime('tomorrow'));
// or this one, which is shorter, but was buggy:
strtotime('Monday this week');
To those, who prefer the "Jedy-way", to work with objects of the DateTime class, the solution is next:
(new \DateTime())->modify('tomorrow')->modify('previous monday')->format('Y-m-d');
or even shorter notation:
\DateTime('Monday this week')
Be carefull, because if you do the same on SQL, you don't need to have any of these tricks in mysql with addition of "tomorrow". Here's how the solution will look:
SELECT DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY) as last_monday;
How can I make it return today's date in that case?
pseudocode:
if (today == monday)
return today;
else
return strtotime(...);
Btw, this trick also could work:
strtotime('last monday', strtotime('tomorrow'));
Late answer, but I thought I would post up this answer (which is actually from a different but related question). It handles the scenario in the question:
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.phpdate
- http://php.net/manual/en/function.date.phpDepending on exactly what you're using it for, this may be useful. Since one second's ambiguity is OK for my requirements, I use:
date( 'Y-m-d 23:59:59', strtotime( 'last sunday' ))
to get midnight on the most recent Monday (or today if today IS Monday).