Converting GMT time to local time using timezone offset in php

只愿长相守 提交于 2019-12-13 03:38:26

问题


I need to display user's activities date as per the current time zone. My approach -

  1. Getting a timezone offset from javascript and storing it to the user's profile table.
  2. When user logged in, getting time zone offset.
  3. current date is working fine with time zone offset-

$offsetDiff = $_SESSION['TimeZone']*60;

$UserDateTime = time() + $offsetDiff;

$currentDate = date('Y-m-d',$UserDateTime);

  1. Dateo other then today is not working properly -

$offsetDiff = $_SESSION['TimeZone']*60;

$UserDateTime = '2014-02-10 08:58:00'; + $offsetDiff;

$monthUser = date('Y-m-d',$UserDateTime);

Can anybody please let me know how can i show correct date according to time zone offset?


回答1:


You can convert a specific offset to a DateTimeZone:

$offset = '-0500';
$isDST = 1; // Daylight Saving 1 - on, 0 - off
$timezoneName = timezone_name_from_abbr('', intval($offset, 10) * 36, $isDST);
$timezone = new DateTimeZone($timezoneName);

Then you can use it in a DateTime constructor, e.g.

$datetime = new DateTime('2012-04-21 01:13:30', $timezone);

or with the setter:

$datetime->setTimezone($timezone);

In the latter case, if $datetime was constructed with a different timezone, the date/time will be converted to specified timezone.



来源:https://stackoverflow.com/questions/21670298/converting-gmt-time-to-local-time-using-timezone-offset-in-php

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