计算不同时区中日期之间的小时数 [英] Calculate hours between dates in different time zones
问题描述
我有一组日期(在格林威治标准时间的不同时区),我想计算第一个日期和最后一个日期之间经过的小时数。
例如,这将是一个日期数组:
[
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
]
我想计算从索引1到2、2到3以及从3到4的日期以来经过的小时数。问题是我不知道如何根据时区进行计算,如果我必须加或减小时才能得到正确的结果。
我需要知道如何开发代码。可能会是这样(因为缺少根据时区进行计算):
$ 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);
}
}
谢谢。
最好的解决方案是使用 DateTime
类。
首先,根据日期字符串创建 \DateTime
对象:
$ datetime1 = new \DateTime($ time);
$ datetime2 = new \DateTime($ times0 [$ i + 1]);
然后,您可以使用 diff()
计算两个日期之间的时差。 code>方法:
$ diff = $ datetime1-> diff($ datetime2);
$ diff
是<$的实例c $ c> \DateTimeInterval ,您可以按自己喜欢的方式设置此差异的格式,例如:
$ diff-> format('%H:%I:%S')
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:
$datetime1 = new \DateTime($time);
$datetime2 = new \DateTime($times0[$i + 1]);
Then you can calculate the difference between two dates using diff()
method:
$diff = $datetime1->diff($datetime2);
$diff
is an instance of \DateTimeInterval
, and you can format this difference any way you like, for example:
$diff->format('%H:%I:%S')
这篇关于计算不同时区中日期之间的小时数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!