SQL DATEDIFF return 错误值
SQL DATEDIFF return wrong value
我们想计算两个 DateTimeOffset 之间的差异,但是,SQL returns 错误的值,我们做错了什么?
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 但它 returns 1
很有趣!正如 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
这里是默认的。
如评论中所述,如果您投射它似乎有效。但不清楚为什么对我来说。
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
我们想计算两个 DateTimeOffset 之间的差异,但是,SQL returns 错误的值,我们做错了什么?
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 但它 returns 1
很有趣!正如 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
这里是默认的。
如评论中所述,如果您投射它似乎有效。但不清楚为什么对我来说。
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