我有这个查询,它正确地将中欧时间返回为 +2 小时。但是,它不会将这两个小时添加到时间中。 如何添加这两个小时的时间(或 x 小时,具体取决于时区(?
DECLARE @targettimezone AS sysname = 'Central European Standard Time'
SELECT convert(datetime2,'2018-10-25T13:43:19.296Z') AT TIME ZONE @targettimezone;
您可以尝试使用 datetimeoffset 而不是datetime2
。
定义一个日期,该日期与具有时区感知能力并基于 24 小时制的一天中的时间组合在一起。
然后将datetimeoffset
转换为DateTime
可以获得您期望的结果。
DECLARE @targettimezone AS sysname = 'Central European Standard Time'
SELECT cast(cast('2018-10-25T13:43:19.296Z' as datetimeoffset) AT TIME ZONE @targettimezone as datetime2);
SQLfiddle
让我们给引擎一些帮助:
DECLARE @targettimezone AS sysname = 'Central European Standard Time'
SELECT convert(datetime2,'2018-10-25T13:43:19.296Z')
AT TIME ZONE 'UTC'
AT TIME ZONE @targettimezone;
我希望您为时间戳指定的格式在本地解释为 UTC,但似乎并非如此。所以以上只是明确说明。¯\_(ツ)_/¯
您需要使用 SQL Server 中的DATEPART
函数捕获偏移量,然后将其应用于 UTC 时间。
DECLARE @utcDateTime DATETIME = '2018-10-25T13:43:19.296Z'
DECLARE @targetTimeZone AS SYSNAME = 'Central European Standard Time'
DECLARE @offsetMinutes INT
DECLARE @targetDateTime DATETIME
--Get the offset value in minutes
SET @offsetMinutes = DATEPART(tz, CONVERT(DATETIME2, @utcDateTime) AT TIME ZONE
@targettimezone)
--Add the offset to the UTC time
SET @targetDateTime = DATEADD(MINUTE, @offsetMinutes, @utcDateTime)
--No you have the value in the target time zone
SELECT @targetDateTime