在MySQL中计算时区的偏移量
MySQL 有没有办法计算任何时区的偏移量? 例如,获取亚洲/加尔各答时区的当地时间。 我想要做的是计算该时区的偏移量并将该偏移量添加到 GMT 以获取当地时间。
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 calculate the offset for this timezone and add that offset to GMT to get the local time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我想知道@ColinM 上面的答案是否安全。 它读取时钟一次还是两次? UTC_TIMESTAMP() 和 NOW() 是否有可能相差一秒? 我不知道,但这可以避免这种情况。
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.
您只需传入偏移量
http://dev .mysql.com/doc/refman/5.1/en/time-zone-support.html
You can just pass in an offset
http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html
如果您想计算时区(例如美国/温哥华)与 UTC 的偏移量,您可以按如下方式进行:
为此,您首先需要将时区信息加载到 mysql 中,如下所述:http://dev.mysql.com/doc/refman/5.0/ en/mysql-tzinfo-to-sql.html
If you want to calculate the offset of a time zone such as America/Vancouver from UTC you can do it as follows:
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
SELECT TIMESTAMPDIFF(HOUR, UTC_TIMESTAMP(), NOW());
如果服务器的时区是 PST,则返回
-8
。SELECT TIMESTAMPDIFF(SECOND, NOW(), UTC_TIMESTAMP());
如果要将上述结果与任何 unix 时间戳进行比较,请将其与 MySQL DateTimes 进行比较。
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.
给予
Giving
偏移量将取决于您感兴趣的时间 - 例如,我目前与 UTC 的偏移量为一小时,但在冬季我的偏移量将为零。
根据 有关 MySQL 时区支持的文档页面,您想使用
convert_tz
函数。 如果您尝试将 UTC 转换为当地时间,请传入“Etc/GMT+0”作为“出发地”时区,并传入“亚洲/加尔各答”作为“目的地”。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".我混淆了 @ColinM 和 @Kenneth Spencer 的答案,因为我想要任意时区的偏移量(以小时为单位):
-
正如 Kenneth 指出的,您需要加载时区信息: http://dev.mysql.com/doc/refman/5.0/en/mysql-tzinfo-to- sql.html
但是你可以做一些有趣的事情,比如一次找到多个时区的偏移量:
给出:
I mixed up @ColinM and @Kenneth Spencer's answers because I wanted the offset of an arbitrary timezone in hours:
-
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:
Giving: