Article
0 comment

Same procedure as last year: switch dates for daylight savings time in PHP

The same procedure every year: part of the world switches to daylight savings time (DST). Don’t get me started on the topic if there is any sense in doing so. We have to deal with it.

There certainly are functions that deliver the correct time for the current timezone. But what if you would like to know the switch dates in advance? The rule for DST switch dates in Germany is quite simple:we switch to summertime at 2:00 in the morning on the last sunday in march and back to wintertime at 2:00 in the morning of the last sunday in october. So these dates are variable.

Here the PHP DateTimeZone comes to the rescue. The steps are simple enough:

  1. Get a DateTimeZone object for the timezone you’re interested in
  2. Get the transition dates for the year you are interested in by specifying the start and end dates to search for
  3. Clean up the returned array, since it always contains the start date itself

And here is a short piece of code to use:

<?php

$year="2018";

// Get start and end date to search for
$t1=strtotime("$year-01-01");
$t2=strtotime("$year-12-31");

$timezone = new DateTimeZone("Europe/Berlin");
$transitions = $timezone->getTransitions($t1, $t2);

// Delete first element since getTransitions() always returns 3 array elements
// and the first is always the start day itself
array_shift($transitions);

print_r($transitions);
?>

The result is an array with two elements. For 2018 in Germany the results are:

Array
(
    [0] => Array
        (
            [ts] => 1521939600
            [time] => 2018-03-25T01:00:00+0000
            [offset] => 7200
            [isdst] => 1
            [abbr] => CEST
        )

    [1] => Array
        (
            [ts] => 1540688400
            [time] => 2018-10-28T01:00:00+0000
            [offset] => 3600
            [isdst] =>
            [abbr] => CET
        )

)