如何将日期时间从UTC转换为本地时间

时间:2018-10-25 15:43:33

标签: sql sql-server timezone utc localtime

我很抱歉,这很简单,我还是SQL的新手,每天都在学习。我想做的是查询

SELECT ProjectName,
       RequestNumber,
       ContactId,
       ContactFirstName,
       ContactLastName,
       RequestReceivedDate,
       RequestCloseDate,
       Category,
       SubCategory,
       AssignedResourceId,
       OwningResourceId,
       RequestSource,
       ClosedImmediatelyFlag,
       RequestStatusCode
FROM dbo.system_requests;

但是我的RequestReceivedDate和RequestCloseDate关闭了5个小时。我在使用供应商数据库时无法创建函数,因此希望在我的select语句中将UTC转换为本地时间,只是不确定这样做的最佳方法?

有想法吗?

2 个答案:

答案 0 :(得分:0)

SQL Server 2016通过AT TIME ZONE'UTC'语句支持时区。您可以这样做:

SELECT ProjectName,
       RequestNumber,
       ContactId,
       ContactFirstName,
       ContactLastName,
       RequestReceivedDate AT TIME ZONE 'UTC',
       RequestCloseDate AT TIME ZONE 'UTC',
       Category,
       SubCategory,
       AssignedResourceId,
       OwningResourceId,
       RequestSource,
       ClosedImmediatelyFlag,
       RequestStatusCode
FROM dbo.system_requests;

您可以在Google上搜索“ AT TIME ZONE”。

答案 1 :(得分:0)

所以我最终这样做了,它奏效了,给了我我想要的东西:

           SELECT CONVERT(
                             DATETIME,
                             SWITCHOFFSET(
                                             CONVERT(DATETIMEOFFSET, system_requests.RequestReceivedDate),
                                             DATENAME(TzOffset, SYSDATETIMEOFFSET())
                                         )
                         ) AS RequestReceivedDate
       ),
       (
           SELECT CONVERT(
                             DATETIME,
                             SWITCHOFFSET(
                                             CONVERT(DATETIMEOFFSET, system_requests.RequestCloseDate),
                                             DATENAME(TzOffset, SYSDATETIMEOFFSET())
                                       )
                         ) AS RequestClosedDate