Everywhere I read about converting time to a user's timezone says that the best method is to store a date and time in UTC then just add the user's timezone offset to this time.
How can I store a date in UTC time? I use the MySQL DATETIME field.
When adding a new record to MySQL in my PHP code I would use now()
to insert into MySQL DATETIME.
Would I need to use something different than now()
to store UTC time?
In short, “ MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME .)” In other words, timezone information is lost in DATETIME columns.
MySQL - UTC_DATE() Function The MYSQL UTC_DATE() is used to get the current UTC date. The resultant value is a string or a numerical value based on the context and, the date returned will be in the 'YYYY-MM-DD' or YYYYMMDD format.
MySQL retrieves and displays DATE values in ' YYYY-MM-DD ' format. The supported range is '1000-01-01' to '9999-12-31' . The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format.
The MySQL NOW() function returns the current date and time in the configured time zone as a string or a number in the 'YYYY-MM-DD HH:MM:DD' or 'YYYYMMDDHHMMSS.
MySQL: UTC_TIMESTAMP()
Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context
PHP: gmdate()
Also PHP date_default_timezone_set()
is used in PHP to set the current time zone for the script. You can set it to the client time zone so all the formatting functions return the time in his local time.
In truth though I had a hard time getting this to work and always stumble into some gotcha. Eg. time information returned from MySQL is not formatted as 'UTC' so strtotime transforms it into a local time if you are not careful. I'm curious to hear if someone has a reliable solution for this problem, one that doesn't break when dates traverse media boundaries (HTTP->PHP->MySQL and MySQL->PHP->HTTP), also considering XML and RSS/Atom.
I would suggest inserting the date in UTC time zone. This will save you a lot of headaches in the future with daylight saving problems.
INSERT INTO abc_table (registrationtime) VALUES (UTC_TIMESTAMP())
When I query my data I use the following PHP script:
<?php while($row = mysql_fetch_array($registration)) { $dt_obj = new DateTime($row['message_sent_timestamp'] ." UTC"); $dt_obj->setTimezone(new DateTimeZone('Europe/Istanbul')); echo $formatted_date_long=date_format($dt_obj, 'Y-m-d H:i:s'); } ?>
You can replace the DateTimeZone
value with one of the available PHP timezones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With