In MySQL caculating offset for a time zone

后端 未结 8 1754
死守一世寂寞
死守一世寂寞 2020-12-08 22:22

Is there a way in MySQL to calculate the offset for any timezone? For example, to get the local time in the timezone Asia/calcutta. What I want to do is calcula

相关标签:
8条回答
  • 2020-12-08 22:34
    SELECT TIME_FORMAT(TIMEDIFF(NOW(), CONVERT_TZ(NOW(), 'Asia/Calcutta', 'UTC')), '%H:%i') AS offset;
    

    Giving

    +--------+
    | offset |
    +--------+
    |  05:30 |
    +--------+
    
    0 讨论(0)
  • 2020-12-08 22:35

    If you want to calculate the offset of a time zone such as America/Vancouver from UTC you can do it as follows:

    SELECT (unix_timestamp() -  unix_timestamp(convert_tz(now(), 'Etc/UTC', 'America/Vancouver'))) / 3600   as offset;
    

    For this to work you will first need to load the time zone information into mysql as outlined here: http://dev.mysql.com/doc/refman/5.0/en/mysql-tzinfo-to-sql.html

    0 讨论(0)
  • 2020-12-08 22:39
    SET time_zone = '-07:00';
    

    You can just pass in an offset

    http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html

    0 讨论(0)
  • 2020-12-08 22:40
    DATEDIFF(NOW(), UTC_TIMESTAMP())
    
    0 讨论(0)
  • 2020-12-08 22:42

    The offset will depend on the time that you're interested in - for instance, I'd currently have an offset of one hour from UTC, but during the winter my offset would be zero.

    Judging by the docs page on MySQL time zone support, you want to use the convert_tz function. If you're trying to convert UTC to local time, pass in "Etc/GMT+0" as the "from" time zone, and "Asia/Calcutta" as the "to".

    0 讨论(0)
  • 2020-12-08 22:45

    I wonder if @ColinM's answer above is safe. Does it read the clock once or twice? Is there any possibility that UTC_TIMESTAMP() and NOW() could be one second apart? I don't know but this would avoid that.

    SET @now = now();
    SET @utc = CONVERT_TZ(@now, 'SYSTEM', '+00:00');
    SELECT TIMESTAMPDIFF(MINUTE, @utc, @now);
    
    0 讨论(0)
提交回复
热议问题