简体   繁体   中英

Converting GMT time to local time using timezone offset in php

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('Ym-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('Ym-d',$UserDateTime);

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

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, eg

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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