Sync Server Time with User's Timezone I have a web application which is being used by users from different parts of the world. In order for users of the site, to be able to view the timestamps in their local time, I've a settings page set up which will allow the user to store their preferred timezone (Europe/Berlin, America/Chicago) etc. When a user is authenticated successfully, value fetches from the DB and stores it in a session.

From what I've read so far, the best practice seems to be to store the datetime value in UTC format when a new record is created in a database and while displaying it, convert it to the user's timezone. So to achieve the following, this is what I'm doing:

if($this-&gt;userIsAuthenticated())
{
   $this-&gt;session-&gt;timezone = "Europe/Berlin"; // this value is coming from db
}

// inserting records
date_default_timezone_set("UTC");
$data = array("created_time"=&gt;date("Y-m-d H:i:s"));
$this-&gt;db-&gt;insert("my_table", $data);

// fetching records
$date_from_db = $row-&gt;created_time;
$display_date = new DateTime($date_from_db , new DateTimeZone('UTC'));
$display_date-&gt;setTimeZone(new DateTimeZone($this-&gt;session-&gt;timezone));
return $display_date-&gt;format("m/d/Y h:i a");


So the workflow is as follows:


Use date_default_timezone_set() for every insert query
Pull the value from the db and set it to UTC using DateTime class
Then set the timzeone to user's timezone


This solution works. But, is this best way of doing it? Or, are there any more modular ways of achieving the same result?
I personally would have saved it as a simple timestamp rather than a date, whether or not that's actually a better idea is debatable, but a timestamp requires half as much space as a datetime and is, imo, much easier to use.

On the client side you can get the user's UTC offset with a simple new Date().getTimezoneOffset() which will return the difference between the user's time and UTC in minutes (multiply by 60 to get seconds). Then you can use PHP's time() function to get the current timestamp and subtract the user's offset.

When you need to display it as a human readable date, PHP's date() can take a timestamp as a second parameter to display a specific time. Timestamps are just a lower level, more efficient way to handle time differences.

if($this-&gt;userIsAuthenticated())
{
   $this-&gt;session-&gt;timezone_offset = "-600"; // this value is coming from db
}

// inserting records
$data = array("created_time"=&gt;time());
$this-&gt;db-&gt;insert("my_table", $data);

// fetching records
$date_from_db = $row-&gt;created_time;
$display_date = date("m/d/Y h:i a", $date_from_db - ($this-&gt;session-&gt;timezone_offset * 60));