简体   繁体   English

给定UTC偏移量和日期时间,我们如何在PHP中找到其UTC日期时间?

[英]Given an UTC offset and a date time, how can we find its UTC date time in PHP?

For example, I have a date time in this format and its UTC offset is +3: 例如,我有一个采用这种格式的日期时间,其UTC偏移为+3:

2011-02-23 05:00:00

So its UTC time is actually: 因此,其UTC时间实际上是:

2011-02-23 02:00:00

But what is the simplest way to do this conversion in PHP? 但是用PHP进行此转换的最简单方法是什么?

I have thought of using the DateTimeZone class but as you can see, I only have the offset but not the timezone name. 我曾考虑过使用DateTimeZone类,但是如您所见,我只有偏移量,没有时区名称。 And to construct a DateTimeZone object, the timezone name is required. 并构造一个DateTimeZone对象,时区名称是必需的。

Maybe there are some better ways without using DateTimeZone class. 也许有一些更好的方法,而不使用DateTimeZone类。

Thanks in advance. 提前致谢。

Could just modify the date based on the offset. 可以仅基于偏移量修改日期。 If you are interested in changing this to other timezones then create the date with the UTC timezone. 如果您有兴趣将其更改为其他时区,请使用UTC时区创建日期。

$date = new DateTime('2011-02-23 05:00:00', new DateTimeZone('UTC'));
$date->modify(sprintf('%s%d hours', $offset < 0 ? '+' : '-', $offset));

Note: This will work even if the offset is a string. 注意:即使偏移量是字符串,这也将起作用。 ie "-3" or "+3" 即“ -3”或“ +3”

Then for example if you wanted to see that time in Melbourne, Australia. 然后,例如,如果您想在澳大利亚墨尔本看到那个时间。

$date->setTimezone(new DateTimeZone('Australia/Melbourne'));
echo $date->format('c');

You can use date() and strtotime() for this. 您可以为此使用date()和strtotime()。

$in = "2011-02-23 05:00:00";
$offset = "-3 hours";
$out = date('Y-m-d H:i:s',strtotime("$in $offset"));

It's also good to note that with this, you aren't restricted on what you're offsetting. 还需要注意的是,使用此功能,您不受抵消的限制。 The strtotime() function lets you do all kinds of wonderful things, like "-2 weeks +3 days ...", etc. strtotime()函数可让您完成各种奇妙的事情,例如“ -2周+3天...”等。

You are also free to get any date format from date(), or just use strtotime() alone to get the timestamp. 您也可以从date()获取任何日期格式,也可以单独使用strtotime()来获取时间戳。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM