问题
I've encountered somehow weird behavior of the strtotime() function when dealing with relative date formats.
I live in a country, where the first day of the week isn't Sunday but Monday instead. This fact should reflected on strtotime()'s output.
The problem is, that no matter what locale I set (i tried en_US locale too), strtotime() just weirds out and neither Monday nor Sunday appears to be in this week's range. See example below.
Today, 2014-02-02 (or 02/02/2014, if you will .. what a nice date) is Sunday. Based on that, i tried to get this week's Monday and Sunday dates. Both were off.
<?php
setlocale(LC_ALL, 'cs_CZ');
$sunday = new DateTime('2014-02-02');
echo '"Today" is Sunday, ' . $sunday->format('Y-m-d') . "\n";
$thisWeekMonday = strtotime('monday this week', $sunday->getTimestamp());
$thisWeekSunday = strtotime('sunday this week', $sunday->getTimestamp());
echo "This week's Monday: " . date('Y-m-d', $thisWeekMonday) . "\n";
echo "This week's Sunday: " . date('Y-m-d', $thisWeekSunday) . "\n";
?>
Code above outputs:
"Today" is Sunday, 2014-02-02
This week's Monday: 2014-02-03
This week's Sunday: 2014-02-09
If strtotime() thought that a week starts with Sunday, it should have returned 2014-02-02 as 'this week sunday', but it didn't. That means, according to strtotime(), a week starts with Monday. In that case, 'this week monday' should be returning 2014-01-27, but it isn't.
This behavior is illogical. Is this a PHP bug? Am I doing something wrong? In case this is a bug, what would be the best way to workaround this issue?
回答1:
Weird, this does in fact seem to be a bug. A work around could involve checking to see if "today is a Sunday". So something like:
$thisWeekSunday = ($sunday->format('w') == 0) ? $sunday->getTimestamp() : strtotime('sunday this week', $sunday->getTimestamp());
来源:https://stackoverflow.com/questions/21517414/strange-behaviour-of-strtotime-when-using-relative-dates-this-week