wuno
wuno

Reputation: 9875

Calculating the php current time by timezone

Background

I am making some updated to a PHP application that is very old. In the application there was an error being thrown because the use of a depreciated function mktime(). I updated this function across the application with time() instead. Once I did this I noticed that when the local time for a user which is calculated by their zip code is displayed, it is one hour behind the actual local time.

I have tracked the time calculation to a function which is below. The time is passed into the value of, $client["localtime"]

Example Code

if (isset($time) && $time) {
    $utc_str = gmdate("M d Y H:i:s", time());
    $utc = strtotime($utc_str);
    if (isset($tznames[ $time["timezone"] ])) {
        $client["timezone"] = $tznames[ $time["timezone"] ];
    } else {
        $client["timezone"] = "Unknown";
    }
    if ($time["daylightsavings"] == "Y" && date("I")) {
        $time["timezone"]--;
    }
    $client["localtime"] = date("g:ia", $utc - ($time["timezone"] * 3600));
} else {
    $client["localtime"] = "Unknown";
    $client["timezone"] = "Unknown";
}

Question

Why is this showing the local time for the client's timezone behind by 1 hour and what must I do to fix it?

Upvotes: 1

Views: 130

Answers (3)

vikas aggarwal
vikas aggarwal

Reputation: 480

if (isset($time) && $time) { 
    $utc_str = gmdate("M d Y H:i:s", time());
    $utc = strtotime($utc_str);
    if (isset($tznames[$time["timezone"]])) { $client["timezone"] = $tznames[$time["timezone"]]; } 
    else { $client["timezone"] = "Unknown"; }
    if ($time["daylightsavings"] == "Y" && date("I")) { $time["timezone"]--; }



   // print_r(($time["timezone"] * 3600).",".$client["timezone"].",".$time["timezone"].",".$utc_str.",".$utc);
       $client["localtime"] = date("g:ia", $utc - ($time["timezone"] * 3600 - 3600));
} else { $client["localtime"] = "Unknown";
$client["timezone"] = "Unknown";}

Check the above code I have subtracted the 3600 from so that it show 1hour late please check if it will work

Upvotes: 1

Dipak
Dipak

Reputation: 39

You can use this code:

$date = new DateTime("now", new DateTimeZone('Australia/Adelaide'));
echo 'Australia/Adelaide: '.$date->format('Y-m-d H:i:s');

$date1 = new DateTime("now", new DateTimeZone('America/Chicago'));
echo 'America/Chicago: '. $date1->format('Y-m-d H:i:s');

Upvotes: 0

Vipul L.
Vipul L.

Reputation: 595

you can use this function

function convertTimeByTimezone($datetime,$timezone='Asia/Kolkata') {
        $given = new DateTime($datetime, new DateTimeZone("UTC"));
        $given->setTimezone(new DateTimeZone($timezone));
        $output = $given->format("Y-m-d H:i:s"); 
        return $output;
}

Upvotes: 0

Related Questions