SQL DATEDIFF返回错误的值

时间:2018-03-23 14:37:03

标签: sql sql-server tsql datetime datetimeoffset

我们想要计算两个DateTimeOffsets之间的差异,但是,SQL返回错误的值,我们做错了什么?

DECLARE @timeInZone1 AS DATETIMEOFFSET
DECLARE @timeInZone2 AS DATETIMEOFFSET
SET @timeInZone1 = '2012-01-13 00:00:00 +1:00';
SET @timeInZone2 = '2012-01-13 23:00:00 +1:00';
SELECT DATEDIFF( day, @timeInZone1, @timeInZone2 );

差异应为0,但返回1

2 个答案:

答案 0 :(得分:1)

正如评论中所说,如果你施展它似乎工作。但不清楚为什么对我来说。

DECLARE @timeInZone1 AS DATETIMEOFFSET
DECLARE @timeInZone2 AS DATETIMEOFFSET
SET @timeInZone1 = '2012-01-13 00:00:00 +1:00';
SET @timeInZone2 = '2012-01-13 23:00:00 +1:00';
SELECT  @timeInZone1 as z1, @timeInZone2 as z2
      , cast(@timeInZone1 as datetime) z1d,  cast(@timeInZone2 as datetime) z2d 
      , DATEDIFF(day, @timeInZone1, @timeInZone2) as diff
      , DATEDIFF(day, cast(@timeInZone1 as datetime), cast(@timeInZone2 as datetime)) as diffdt;

z1                                 z2                                 z1d                     z2d                     diff        diffdt
---------------------------------- ---------------------------------- ----------------------- ----------------------- ----------- -----------
2012-01-13 00:00:00.0000000 +01:00 2012-01-13 23:00:00.0000000 +01:00 2012-01-13 00:00:00.000 2012-01-13 23:00:00.000 1           0

答案 1 :(得分:0)

非常有趣!正如Jeroen Mostert评论的那样,datetimeoffset值似乎转换为UTC:

select datediff(day, '2017-01-01 0:00 +1:00', '2017-01-01 1:00 +1:00') --> 1

转换为UTC会使第一个值为“2016-12-31 23:00'”,这是前一天。

但正常datetime值未转换为UTC:

select datediff(day, '2017-01-01 0:00', '2017-01-01 1:00') --> 0

生活在UTC + 1中,令人惊讶的是,添加+1:00会产生不同的结果。毕竟+1:00是默认值。