转换为UTC而不更改php时区设置 [英] convert to UTC without changing php timezone settings
问题描述
如何在不更改默认时区的情况下在php中转换日期字符串的时区.我想将其本地转换为仅显示.不应更改php时区设置.
How can I convert the time zone of a date string in php without changing the default time zone. I want to convert it locally to display only. The php time zone settting should not be modified.
我的源时间是UTC字符串,我想将其转换为其他格式,将时区保留为UTC,但是php将其转换为本地时区. 我使用的代码是:
My source time is a UTC string, I want to convert it to a different format, retaining the time zone as UTC, but php is converting it to local timezone. The code I used was:
date('Y-m-d H:i::s',strtotime($time_str));
如何保留时区?
推荐答案
$src_tz = new DateTimeZone('America/Chicago');
$dest_tz = new DateTimeZone('America/New_York');
$dt = new DateTime("2000-01-01 12:00:00", $src_tz);
$dt->setTimeZone($dest_tz);
echo $dt->format('Y-m-d H:i:s');
请注意,如果源时间是UTC,则可以将一行更改为此:
Note that if the source time is UTC, you can change the one line to this:
$dt = new DateTime("2000-01-01 12:00:00 UTC");
您似乎想去 UTC.在这种情况下,只需将"UTC"
用作$dest_tz
构造函数的参数,并使用原始代码块. (当然,如果$src_tz
参数与默认时区相同,则可以省略.)
Looks like you want to go to UTC. In that case, just use "UTC"
as the parameter to the $dest_tz
constructor, and use the original block of code. (And of course, you can omit the $src_tz
parameter if it is the same as the default time zone.)
这篇关于转换为UTC而不更改php时区设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!