Can MySQL convert a stored UTC time to local timezone?

前端 未结 7 1316
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 19:51

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



        
7条回答
  •  猫巷女王i
    2020-12-02 20:11

    1. Correctly setup your server:

    On server, su to root and do this:

    # mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql mysql
    

    (Note that the command at the end is of course mysql and you're sending it to a table with the same name mysql.)

    So, if you # ls /usr/share/zoneinfo you will see all the time zone info on ubuntu or almost any unixish server.

    (BTW that's the convenient way to easily find out the exact official name of some time zone.)

    2. It's then trivial in mysql:

    For example

    mysql> select ts, CONVERT_TZ(ts, 'UTC', 'Pacific/Tahiti') from example_table ;
    +---------------------+-----------------------------------------+
    | ts                  | CONVERT_TZ(ts, 'UTC', 'Pacific/Tahiti') |
    +---------------------+-----------------------------------------+
    | 2020-10-20 16:59:57 | 2020-10-20 06:59:57                     |
    | 2020-10-20 17:02:59 | 2020-10-20 07:02:59                     |
    | 2020-10-20 17:30:08 | 2020-10-20 07:30:08                     |
    | 2020-10-20 18:36:29 | 2020-10-20 08:36:29                     |
    | 2020-10-20 18:37:20 | 2020-10-20 08:37:20                     |
    | 2020-10-20 18:37:20 | 2020-10-20 08:37:20                     |
    | 2020-10-20 19:00:18 | 2020-10-20 09:00:18                     |
    +---------------------+-----------------------------------------+
    

提交回复
热议问题