Search code examples
phpdatetimeunix-timestampdst

PHP Date 4 Weeks Ago


I have the following code which outputs 20191027 as a result.

If I amend the 2nd line (i.e. set timezone to Auckland), it gives me the result 20191028. Why is this?

date_default_timezone_set("Europe/London");
#date_default_timezone_set("Pacific/Auckland");

$date_format =  'Ymd';

$day = "Sunday 4 week ago";
$start_of_the_week = strtotime($day);

$next_day = $start_of_the_week + (60 * 60 * 24 * 1);
$next_day = date($date_format, $next_day);

echo $next_day;

Check 2 outputs:


Solution

  • In Europe/London timezone...

    DST ended on Sun 27-Oct-2019 at 02:00:00 A.M. when local clocks were set backward 1 hour

    Keep in mind that that strtotime operates on unix timestamps where there is no concept of DST but the date function adjusts the unix timestamp to local timezone when formatting it. So:

    $start_of_the_week = strtotime("Sunday 4 week ago"); // $start_of_the_week is some unix timestamp
    echo date("Y-m-d H:i:s", $start_of_the_week);        // 2019-10-27 00:00:00 Europe/London time
    
    $next_day = $start_of_the_week + (60 * 60 * 24 * 1); // you're adding 24 hours to a unix timestamp
    echo date("Y-m-d H:i:s", $next_day);                 // 2019-10-27 23:00:00 Europe/London time
    

    And 2019-10-27 23:00:00 is still a Sunday. The solution is to add days instead of hours:

    $next_day = strtotime("+1 day", $start_of_the_week); // 2019-10-28 00:00:00