Search code examples
mysqldatetimeutc

Store a UTC date with PHP to MySQL


I have a mobile app and rest service. The mobile app will generate and provide the web service a UTC date time and time zone. I need to store both values into mysql using php.

I am acquiring the date time from a remote source, so I cannot use mysql's UTC_TIMESTAMP() to generate the 'current' utc time.

I have a table with 2 columns, created (DATETIME) and timezone (VARCHAR)

In PHP, I will collect the following:

$created = "2010-09-30 12:31:10"; //Actual UTC time
$timezone = "America/Los_Angeles"

How would the INSERT statement be so it stores $created, as is (UTC), without it storing it as my server's default timezone?

Would I have to convert it from UTC to my server's local time in PHP or can it be side stepped some how in MySQL?


Solution

  • As far as I know, MySQL doesn't support time zone information on date columns, like for instance, PostgreSQL do.

    Why can't you just store the date as is? I'm fairly sure that no conversion will take place. And also, why do you need the timezone info anyway? Isn't it more relevant to convert it to local time upon display, later on? For the specific user that is viewing the information?

    "The current time zone setting does not affect values displayed by functions such as UTC_TIMESTAMP() or values in DATE, TIME, or DATETIME columns. Nor are values in those data types stored in UTC; the time zone applies for them only when converting from TIMESTAMP values. If you want locale-specific arithmetic for DATE, TIME, or DATETIME values, convert them to UTC, perform the arithmetic, and then convert back. " source https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html

    Meaning, MySQL only utilize the time zone information in order to return local time from TIMESTAMP() and similar functions, not for on the fly conversion of data inserted or selected.