Reputation: 833
I store time in UTC timezone in MySQL DATETIME field. I want to convert all these (when using them in PHP) to user defined timezone. I know I can do it with php DateTime::setTimezone, but it would require to do it each for each one of them.
Is there some global way to tell php that all datetimes from mysql are UTC and convert them automatically to the user timezone?
Upvotes: 2
Views: 4648
Reputation: 33502
When you store them into the database, store the table column as a unix timestamp. These are all UTC. Then just apply whatever user specified offset you want.
Here is an interesting StackOverflow question which is likely to help you with it.
You can also use the MySQL Unix_Timestamp function to query data easily by generating the right int when doing comparisons.
Edit: If you are certain that you want to convert all the datetimes from the database each time you use them, just write a simple function that gets the datetime and adds the correct offset for the user, then simply call that function each time you pluck a datetime from the database. like the code below:
<?php
// Assuming that $_SESSION['UserOffset'] is storing the user's timezone eg
// $_SESSION['UserOffset'] = new DateTimeZone("Europe/Prague");
function convert_time_zone($timeFromDatabase_time)
{
$userTime = new DateTime($timeFromDatabase, new DateTimeZone('UTC'));
$userTime->setTimezone(new DateTimeZone($_SESSION['UserOffset']));
return $userTime->format('Y-m-d H:i:s');
// or return $userTime; // if you want to return a DateTime object.
}
?>
Upvotes: 3