convert to UTC without changing php timezone settings

僤鯓⒐⒋嵵緔 提交于 2019-12-30 06:56:25

问题


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.

EDIT: 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));

How do I retain timezone?


回答1:


$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');

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");

Edit: 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.)



来源:https://stackoverflow.com/questions/10711597/convert-to-utc-without-changing-php-timezone-settings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!