Reputation: 5846
When I try to fetch a timestamp for X days after last sunday, I get an odd result.
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday +5 days")); => 2014-05-09
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday +6 days")); => 2014-05-10
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday +7 days")); => 2014-05-18
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday +8 days")); => 2014-05-19
Why does it jump over a week? In what order is it reading the parameters?
Tested in php: 5.5.4, 5.5.9, and 5.5.10.
The problem occurs only if the startdate is a sunday.
Upvotes: 1
Views: 282
Reputation: 872
@puggan-se Such complexity! It is confusing me and so PHP, let me KISS it for PHP.
$sample_date = strtotime('2014-05-11');
$last_sunday = strtotime('last sunday', $sample_date);
echo date("Y-m-d\n", strtotime("+5 days", $last_sunday)); // => 2014-05-09
echo date("Y-m-d\n", strtotime("+6 days", $last_sunday)); // => 2014-05-10
echo date("Y-m-d\n", strtotime("+7 days", $last_sunday)); // => 2014-05-11
echo date("Y-m-d\n", strtotime("+8 days", $last_sunday)); // => 2014-05-12
Upvotes: 1
Reputation: 4715
Since 2014-05-11 was actually a sunday, last sunday jumps one week, since you want the sunday before the date specified, when you say "last sunday". You might need a check wheter the absolute date you use is a sunday or not; and act accordingly.
strtotime can act unpredictable here, because you are mixing different statements into one so I suggest something on the lines of
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday")+5*86400);
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday")+6*86400);
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday")+7*86400);
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday")+8*86400);
You can give the base date to strtotime as second parameter, to make things even more clear:
echo date("Y-m-d\n", strtotime("last sunday", strtotime('2014-05-11'))+5*86400);
echo date("Y-m-d\n", strtotime("last sunday", strtotime('2014-05-11'))+6*86400);
echo date("Y-m-d\n", strtotime("last sunday", strtotime('2014-05-11'))+7*86400);
echo date("Y-m-d\n", strtotime("last sunday", strtotime('2014-05-11'))+8*86400);
Upvotes: 1
Reputation: 3372
As per PHP.NET strtotime changelog:
Prior to PHP 5.3.0, relative time formats supplied to the time argument of strtotime() such as this week, previous week, last week, and next week were interpreted to mean a 7 day period relative to the current date/time, rather than a week period of Monday through Sunday.
http://sandbox.onlinephpfunctions.com/code/4bc6054b173ac81b3fd6ddf535f4fe4bfc06e98f
Test for php versions > 5.3 and < 5.3, you can see the difference.
Upvotes: 1