MySQL and PHP working with user timezones

Issue

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?

Solution

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.
    }


?>

Answered By – Fluffeh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published