Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can MySQL convert a stored UTC time to local timezone?

Can MySQL convert a stored UTC time to local time-zoned time directly in a normal select statement?

Let's say you have some data with a timestamp (UTC).

CREATE TABLE `SomeDateTable` (   `id`    int(11) NOT NULL auto_increment,   `value` float NOT NULL default '0',   `date`  datetime NOT NULL default '0000-00-00 00:00:00',   PRIMARY KEY  (`id`) ) 

Then when I

"select value, date from SomeDateTable"; 

I of course get all the dates as in their stored UTC form.

But let's say that I would like to have them in another timezone (with DST), can I then add some magic to the select query so that I get all the dates back in the selected timezone?

"select value, TIMEZONE(date, "Europe/Berlin") from SomeDateTable"; 

Or must I do this in some other layer on top, like in some php code? (it seems to be how most people have solved this problem).


If your MySQL installation allows you to use CONVERT_TZ it is a very clean solution, this example shows how to use it.

SELECT CONVERT_TZ( '2010-01-01 12:00', 'UTC', 'Europe/Stockholm' ) 

However I don't know if this is a good way since some MySQL installation is missing this function, use with care.

like image 311
Johan Avatar asked Feb 02 '10 20:02

Johan


People also ask

How do I convert UTC to time in MySQL?

Here's an example to convert EST to UTC timezone by specifying time zone names instead of offset values. mysql> select convert_tz('2020-09-17 03:00:00','US/Eastern','UTC'); Hopefully, now you can convert datetime to UTC in MySQL. Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards.

How do I change timezone in MySQL?

MySQL CONVERT_TZ() function In MySQL the CONVERT_TZ() returns a resulting value after converting a datetime value from a time zone specified as the second argument to the time zone specified as the third argument. This function returns NULL when the arguments are invalid.

Does MySQL store datetime as UTC?

time information returned from MySQL is not formatted as 'UTC' so strtotime transforms it into a local time if you are not careful.


1 Answers

Yup, there's the convert_tz function.

like image 70
Stephen Fischer Avatar answered Sep 17 '22 12:09

Stephen Fischer