在时区,处理多个时区

时间:2017-09-24 11:20:33

标签: sql-server azure-sql-database

我正在创建一个应用程序,该应用程序需要能够处理来自多个时区的用户并正确显示其特定时区的日期。

我已经创建了以下代码作为我得到的示例,但我对于处理时区问题的正确方法有点困惑。

最好通过将数据库中的所有日期存储为UTC并相应地使用AT TIME ZONE来实现此目的,还是应该采用其他方式?

Create Table #Test
(
    SampleDate datetimeoffset(7) 
)

Create Table #Test2
(
    SampleDate datetimeoffset(7) 
)

Create Table #Test3
(
    SampleDate datetime
)

insert into #Test select getdate()
insert into #Test2 select getdate() AT TIME ZONE 'AUS Eastern Standard Time' 
insert into #Test3 select getdate()


select 
    SampleDate, 
    SampleDate AT TIME ZONE 'AUS Eastern Standard Time',
    SampleDate AT TIME ZONE 'AUS Central Standard Time',
    SampleDate AT TIME ZONE 'Aus Central W. Standard Time'
from #Test

select 
    SampleDate, 
    SampleDate AT TIME ZONE 'AUS Eastern Standard Time',
    SampleDate AT TIME ZONE 'AUS Central Standard Time',
    SampleDate AT TIME ZONE 'Aus Central W. Standard Time'
from #Test2

select 
    SampleDate, 
    SampleDate AT TIME ZONE 'AUS Eastern Standard Time',
    SampleDate AT TIME ZONE 'AUS Central Standard Time',
    SampleDate AT TIME ZONE 'Aus Central W. Standard Time'
from #Test3

drop table #Test
drop table #Test2
drop table #Test3

测试结果

2017-09-24 10:59:47.4233333 +00:00  
2017-09-24 20:59:47.4233333 +10:00  
2017-09-24 20:29:47.4233333 +09:30  
2017-09-24 19:44:47.4233333 +08:45

Test2结果

2017-09-24 10:59:47.4230000 +10:00  
2017-09-24 10:59:47.4230000 +10:00  
2017-09-24 10:29:47.4230000 +09:30  
2017-09-24 09:44:47.4230000 +08:45

Test3结果

2017-09-24 10:59:47.423 
2017-09-24 10:59:47.423 +10:00  
2017-09-24 10:59:47.423 +09:30  
2017-09-24 10:59:47.423 +08:45

1 个答案:

答案 0 :(得分:0)

SQL Azure数据库始终使用UTC时间。因此,您应该使用datetimeoffset。

您还应该使用sysdatetimeoffset()而不是使用getdate()来捕获系统日期。

当您从数据库表中检索日期时,您应该使用“AT TIME ZONE”。

希望这有帮助。