如何在MySQL中以正确的方式处理存储的UTC日期转换(夏令时)?

时间:2017-08-14 14:27:23

标签: mysql datetime

我使用datetime将用户创建的日期保存为数据库中的build.gradle 示例:UTC_TIMESTAMP()

我知道贝娄会返回正确的结果。

CreatedDate datetime,

我怀疑旧数据是否需要检查它是否在夏令时下。在那之后进行适当的计算,这是我的主要疑问。它是否需要。请清楚解释一下?

例如:

select  convert_tz(utc_timestamp(),'+00:00',@@session.time_zone);



出于报告目的,我使用select case when ( month(utc_timestamp())<6 and month(CreatedDate)<6 ) or ( month(utc_timestamp())>6 and month(CreatedDate)>6)) then convert_tz(CreatedDate ,'+00:00',@@session.time_zone) when ( month(utc_timestamp())<6 and month(CreatedDate)>6 ) then convert_tz(CreatedDate,'+00:00',@@session.time_zone) -- require to decrease the @@session.time_zone with 1 hour else convert_tz(CreatedDate,'+00:00',@@session.time_zone) -- require to increase the @@session.time_zone with 1 hour end as CreatedDate from tbluser; 否则我会将CreatedDate(无转换)提供给前端开发人员。但我仍然怀疑它是否需要检查夏令时并转换为旧数据?

上面的查询有错,但我要求逻辑。

1 个答案:

答案 0 :(得分:1)

来自mysql documentation

  

timezone 值可以多种格式提供,其中没有一种格式区分大小写:

     
      
  • 'SYSTEM'表示时区应与时区相同   系统时区。

  •   
  • 该值可以作为表示与UTC的偏移量的字符串给出,例如   '+10:00''-6:00'

  •   
  • 该值可以作为命名时区给出,例如   'Europe/Helsinki''US/Eastern''MET'。命名时区可以   仅在mysql数据库中的时区信息表时使用   已创建并填充。

  •   

如果您的@@session.time_zone是第一种或第三种形式,则已将DST考虑在内。

在第二种形式中,您只有一个固定的UTC偏移量,因此您无法真正假设任何DST适用。即使你可以,它肯定不会遵循你所写的逻辑。请记住,DST并不适用于整个世界,对于那些使用它的人来说,国家之间有不同的开始和结束日期和时间。

因此,您应 编写任何自定义DST调整。让convert_tz完成它的工作。