Rajat Tripathi
Rajat Tripathi

Reputation: 1

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('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?

Upvotes: 0

Views: 1435

Answers (1)

hizbul25
hizbul25

Reputation: 3849

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.

Upvotes: 1

Related Questions