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->userIsAuthenticated())
{
$this->session->timezone = "Europe/Berlin"; // this value is coming from db
}
// inserting records
date_default_timezone_set("UTC");
$data = array("created_time"=>date("Y-m-d H:i:s"));
$this->db->insert("my_table", $data);
// fetching records
$date_from_db = $row->created_time;
$display_date = new DateTime($date_from_db , new DateTimeZone('UTC'));
$display_date->setTimeZone(new DateTimeZone($this->session->timezone));
return $display_date->format("m/d/Y h:i a");
So the workflow is as follows:
Use
date_default_timezone_set()
for every insert queryPull the value from the db and set it to UTC using
DateTime
classThen 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?