In MySQL caculating offset for a time zone

后端 未结 8 1755
死守一世寂寞
死守一世寂寞 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:49

    I mixed up @ColinM and @Kenneth Spencer's answers because I wanted the offset of an arbitrary timezone in hours:

    TIMESTAMPDIFF(HOUR, UTC_TIMESTAMP(), CONVERT_TZ(UTC_TIMESTAMP(), "UTC", "America/Denver"))
    

    -

    SELECT ROUND(TIMESTAMPDIFF(MINUTE, UTC_TIMESTAMP(), CONVERT_TZ(UTC_TIMESTAMP(), "Etc/UTC", "Asia/Kolkata"))/60,1)
    

    As Kenneth pointed out you'll need to load the timezone info: http://dev.mysql.com/doc/refman/5.0/en/mysql-tzinfo-to-sql.html

    But then you can do fun things like find the offset for multiple timezones at once:

    SELECT Name,
    TIMESTAMPDIFF(HOUR, UTC_TIMESTAMP(), CONVERT_TZ(UTC_TIMESTAMP(), "Etc/UTC", Name)) as Offset
    FROM mysql.time_zone_name 
    WHERE (Name IN ('America/Vancouver', 'Etc/UTC', 'America/Denver'))
    

    Giving:

    +-------------------+--------+
    | Name              | Offset |
    +-------------------+--------+
    | America/Denver    |     -6 |
    | America/Vancouver |     -7 |
    | Etc/UTC           |      0 |
    +-------------------+--------+
    
    0 讨论(0)
  • 2020-12-08 22:55

    SELECT TIMESTAMPDIFF(HOUR, UTC_TIMESTAMP(), NOW());

    If the server's timezone is PST this will return -8.

    SELECT TIMESTAMPDIFF(SECOND, NOW(), UTC_TIMESTAMP());

    Add the result of the above to any unix timestamp if you want to compare it to MySQL DateTimes.

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