One possibility to calculate the difference between two given hours is to use DateTime::diff(). At the time of writing this answer there was a PHP bug and you had to convert to UTC before:
<?php
$zone = new DateTimeZone('Europe/Madrid');
$start = new DateTime('2013-03-31 1:59:00 ', $zone);
$end = new DateTime('2013-03-31 3:00:00', $zone);
// Workaround for bug #63953
// No longer required since PHP/5.6.0, PHP/5.5.8 or PHP/5.4.24
$start->setTimeZone(new DateTimeZone('UTC'));
$end->setTimeZone(new DateTimeZone('UTC'));
$difference = $start->diff($end);
echo $difference->format('%H:%I:%S');
... prints 00:01:00
because that's when DST started in Western Europe.
You can also use Unix timestamps, which represent a fixed moment in time thus do not depend on time zones:
<?php
$zone = new DateTimeZone('Europe/Madrid');
$start = new DateTime('2013-03-31 1:59:00 ', $zone);
$end = new DateTime('2013-03-31 3:00:00', $zone);
$difference = $end->format('U') - $start->format('U');
echo "$difference seconds";
... prints 60 seconds
.
Edit #1: What do you mean? My snippet contains sample data so you can test it—in real code you'll use your real data. You can (and should) set the correct time zone as default so you don't need to specify it every time. But even if you don't, the server's time zone will never change—even if you decide to physically move the computer to another state or country several times a year you can still opt for a fixed time zone of your choice (your app's time zone can be different from your server's).
If you really want a solution that requires you to change the code manually twice a year (for whatever the reason, maybe to charge maintenance fees), you'd better skip date/time functions and use strings; otherwise you'll risk PHP doing the calculations for you.
Edit #2:
$start
and$end
represent your data. I chose sample data one minute before DST just to illustrate that the diff code works fine. It's the same as when you see<?php echo "Hello, World!"; ?>
in a PHP tutorial:Hello, World!
is sample data to illustrate howecho
works but you don't have to useHello, World!
when you write your app.To convert from
GMT
toEST
with PHP you create a date that belongs toGMT
:$date = new DateTime('14:30', new DateTimeZone('GMT')); echo 'GMT: ' . $date->format('r') . PHP_EOL; // GMT: Thu, 07 Nov 2013 14:30:00 +0000
... and then switch to
EST
:$date->setTimeZone(new DateTimeZone('EST')); echo 'EST: ' . $date->format('r') . PHP_EOL; // EST: Thu, 07 Nov 2013 09:30:00 -0500
However, if your original dates are in GMT, converting them to EST before substracting them does not provide any benefit.