我有这个查询,可以正确返回中欧时间+2小时。但是,它不会增加这两个小时的时间。 如何添加这两个小时的时间(或x小时,取决于时区)?
DECLARE @targettimezone AS sysname = 'Central European Standard Time'
SELECT convert(datetime2,'2018-10-25T13:43:19.296Z') AT TIME ZONE @targettimezone;
答案 0 :(得分:3)
您可以尝试使用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);
答案 1 :(得分:2)
让我们为引擎提供一些帮助:
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,但事实并非如此。因此,上述内容只是明确的。 ¯\ _(ツ)_ /¯
答案 2 :(得分:0)
您需要使用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