• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 352
  • Last Modified:

Client-side timezone handling problems

I use the function below to set the timezone in PHP based on the offset returned by the client browser (thanks to jason at jasonpriem dot com

But, my database queries don't seem to return different date displays... do I need to tell mySQL separately from PHP? I thought if I told PHP, PHP make sure the DB also operates in the right timezone. E.g., a query that records 1pm MST (my timezone), is displayed as 1pm no matter what I set the default timezone to.
function set_tz_by_offset($offset) {
        $offset = $offset*60*60;
        $abbrarray = timezone_abbreviations_list();
        foreach ($abbrarray as $abbr) {
            //echo $abbr."<br>";
                foreach ($abbr as $city) {
                    //echo $city['offset']." $offset<br>";
                        if ($city['offset'] == $offset) { // remember to multiply $offset by -1 if you're getting it from js
                               date_default_timezone_set($city['timezone_id']);
                               return true;
                        }
                }
        }
    date_default_timezone_set("ust");
       return false;
       }

Open in new window

0
metalaureate
Asked:
metalaureate
  • 2
1 Solution
 
nasirbestCommented:
I am not aware with your database query. but I think following solution can help you.

1. while saving in database never use regular dates instead use unix timestamp, and don't worry about timezones because unix timestamp does not depends on zone setting.

2. and when you have to display date back to user, get timestamp from db, add offset, and then convert timestamp into regular date.


here is sample code
<?php

// save some date
mysql_query('INSERT INTO tbl_my (column1) VALUES (UNIX_TIMESTAMP())');


// display date back to user
$test_time = mysql_result(mysql_query('SELECT column1 FROM tbl_my LIMIT 1'));
$test_time += $offset;  // add timezone difference (between server and client) in timestamp

echo date('Y-m-d H:i:s', $test_time);

?>

Open in new window

0
 
metalaureateAuthor Commented:
I wouldn't mind some other experts weighing on this as it's rather critical to a lot of code...
0
 
metalaureateAuthor Commented:
Thanks!
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now