Can MySQL convert a stored UTC time to local timezone?

前端 未结 7 1308
被撕碎了的回忆
被撕碎了的回忆 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条回答
  • 2020-12-02 20:10

    For those unable to configure the mysql environment (e.g. due to lack of SUPER access) to use human-friendly timezone names like "America/Denver" or "GMT" you can also use the function with numeric offsets like this:

    CONVERT_TZ(date,'+00:00','-07:00')
    
    0 讨论(0)
  • 2020-12-02 20:10

    I am not sure what math can be done on a DATETIME data type, but if you are using PHP, I strongly recommend using the integer-based timestamps. Basically, you can store a 4-byte integer in the database using PHP's time() function. This makes doing math on it much more straightforward.

    0 讨论(0)
  • 2020-12-02 20:11
    select convert_tz(now(),@@session.time_zone,'+03:00')
    

    For get the time only use:

    time(convert_tz(now(),@@session.time_zone,'+03:00'))
    
    0 讨论(0)
  • 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                     |
    +---------------------+-----------------------------------------+
    
    0 讨论(0)
  • 2020-12-02 20:14

    Yup, there's the convert_tz function.

    0 讨论(0)
  • 2020-12-02 20:15

    I propose to use

    SET time_zone = 'proper timezone';
    

    being done once right after connect to database. and after this all timestamps will be converted automatically when selecting them.

    0 讨论(0)
提交回复
热议问题