php add or subtract timezone offset

ぐ巨炮叔叔 提交于 2019-12-21 22:16:59

问题


I have some dates stored in gmt in a mysql db.
Say the clients timezone offset was -540; how would I correct the datetime coming from the database to reflect that? Is there a handy function I can put the date through, or am I going to need to add or subtract accordingly.


回答1:


Since you have the data items in GMT format, you will have to convert them to time stamps, using strtotime, more info here: http://php.net/manual/en/function.strtotime.php Once you have the time stamp, you can subtract the offset (540 times 60 seconds) from it, and then convert the result to a new date string, using date, more info here: http://php.net/manual/en/function.date.php

Here is one version of the code that could to this:

$dbValue = $row['date']; 
$timestamp = strtotime($dbValue) - (540*60);
$result = date("Y-m-d H:i:s", $timestamp);



回答2:


Perhaps this Snippet will help you:

$format = 'Y-m-d';
$obj = new DateTime();
$date = date($format, strtotime($obj->format('Y-m-d H:i:s')) - $obj->format('Z'));

See also http://www.php.net/manual/en/class.datetime.php for further readings.



来源:https://stackoverflow.com/questions/9580394/php-add-or-subtract-timezone-offset

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