Sridhar
Sridhar

Reputation: 2228

PHP 5.2.17: convert local time to GMT and GMT to local time

In my application, I just want to convert a local time to GMT and GMT to local time. I got the following two methods to do so.

function GmtTimeToLocalTime($date) {
    $gmt_time = date("Y-m-d H:i:s", $date);
    date_default_timezone_set("UTC");
    $timestamp_in_gmt = strtotime($gmt_time);
    date_default_timezone_set('Asia/Calcutta');
    $local_time = date("Y-m-d H:i:s", $timestamp_in_gmt);
    //date_default_timezone_set("UTC");
    return $local_time;
}

function LocalTimeToGmtTime($date) {
    $local_time = date("Y-m-d H:i:s", $date);
    date_default_timezone_set('Asia/Calcutta');
    $timestamp_in_localtime = strtotime($local_time);
    date_default_timezone_set("UTC");
    $gmt_time = date("Y-m-d H:i:s", $timestamp_in_localtime);
    //date_default_timezone_set('Asia/Calcutta');
    return $gmt_time;
}

But i got this date 1970-01-01 for all the inputs.

Please provide me the correct way. Thanks in advance

Upvotes: 1

Views: 4257

Answers (3)

rushil
rushil

Reputation: 576

Pass latlong in following function to get timezone.

function getTimezoneGeo($latForGeo, $lngForGeo) {
        $json = file_get_contents("http://api.geonames.org/timezoneJSON?lat=".$latForGeo."&lng=".$lngForGeo."&username=demo");
        $data = json_decode($json);
        $tzone=$data->timezoneId;
        return $tzone;
    }

Upvotes: 0

artragis
artragis

Reputation: 3713

Perhaps if you try with DateTime object you would get better result :

<?php
 function GmtTimeToLocalTime($time) {
    $date =  new DateTime(date('Y-m-d h:i:s',$time),new DateTimezone('UTC'));
    $date->setTimezone(new \DateTimezone('Asia/Calcutta'));
    return $date->format("Y-m-d H:i:s");
 }

Upvotes: 3

Fylhan
Fylhan

Reputation: 677

A shortcut should be to look at DateTime and use DateTime::setTimezone to modify the timezone from GMT to local time, and vice-versa.

Edit: and of course, you can fill this DateTime with your timestamp using DateTime::setTimestamp or DateTime::createFromFormat.

Upvotes: 2

Related Questions