I have an array of dates (in different time zones GMT) and I would like to calculate the hours that have elapsed between the first and the last date.
For example, this would be an array of dates:
[
1 => 2016-06-05T08:45:00.000+02:00,
2 => 2016-06-05T09:55:00.000+02:00,
3 => 2016-06-05T12:10:00.000+02:00,
4 => 2016-06-05T14:25:00.000-04:00
]
I want to calculate the hours that have elapsed since the date with index 1 to 2, 2 to 3 and from 3 to 4. The problem is I do not know how to calculate according to the time zone, if I must add or subtract hours to get the right result.
I need to know how it is calculated to develop the code. It would be something (for lack of calculated according to the time zone):
$tIda = 0;
foreach ($times0 as $i => $time)
{
if ($i < sizeof($times0) - 1)
{
$datetime1 = strtotime(substr($time, 0, 10) . ' ' . substr($time, 11, 8));
$datetime2 = strtotime(substr($times0[$i + 1], 0, 10) . ' ' . substr($times0[$i + 1], 11, 8));
$interval = abs($datetime2 - $datetime1);
$tIda += round($interval / 60);
}
}
Thanks.
The best solution would be to use
DateTime
classes.First, you create
\DateTime
objects from date strings:Then you can calculate the difference between two dates using
diff()
method:$diff
is an instance of\DateTimeInterval
, and you can format this difference any way you like, for example:strtotime()
parses time zones just fine:... and once you have a Unix timestamp you can forget about time zones because a Unix timestamp is a fixed moment in time (not a relative local time).
Since you've added tags for the
DateTime
class:You should use the
DateTime
andDateInterval
classes. They will handle all the timezome hazzle for you.