[英](Transact-SQL) DATEDIFF and leap years
I have a problem with DATEDIFF function. 我对DATEDIFF函数有问题。
My date format is dd/mm/yyyy
. 我的日期格式是dd/mm/yyyy
。
@START_DATE = 01/02/2004
@END_DATE = 29/01/2014
The query (DATEDIFF(DAY,@START_DATE,@END_DATE) / 365)
return 10
, but the number of correct years is 9
. 查询(DATEDIFF(DAY,@START_DATE,@END_DATE) / 365)
返回10
,但是正确的年数是9
。 This happens because my query does not consider leap years. 发生这种情况是因为我的查询未考虑leap年。
What I can do to keep an accurate count? 我该怎么做才能保持准确的计数? Thanks. 谢谢。
I believe the following logic does what you want: 我相信以下逻辑可以满足您的需求:
datediff(year,
@START_DATE - datepart(dayofyear, @START_DATE) + 1,
@END_DATE - datepart(dayofyear, @START_DATE) + 1
) as d2
Note: This treats that dates as datetime
, because arithmetic is easier to express. 注意:这会将日期视为datetime
,因为算术更易于表达。 You can also write this as: 您也可以这样写:
datediff(year,
dateadd(day, - datepart(dayofyear, @START_DATE) + 1, @START_DATE),
dateadd(day, - datepart(dayofyear, @START_DATE) + 1, @END_DATE)
) as d2
The following query is a demonstration: 以下查询是一个演示:
select datediff(year,
startdate - datepart(dayofyear, startdate) + 1,
enddate - datepart(dayofyear, startdate) + 1
) as d2
from (select cast('2004-02-01' as datetime) as startdate,
cast('2014-01-31' as datetime) as enddate
union all
select cast('2004-02-01' as datetime) as startdate,
cast('2014-02-01' as datetime) as enddate
) t
You can create a function to address that: 您可以创建一个函数来解决以下问题:
CREATE FUNCTION [dbo].[getYears]
(
@START_DATE datetime,
@END_DATE datetime
)
RETURNS int
AS
BEGIN
DECLARE @yrs int
SET @yrs =DATEDIFF(year,@START_DATE,@END_DATE)
IF (@END_DATE < DATEADD(year, @yrs, @START_DATE))
SET @yrs = @yrs -1
RETURN @yrs
END
Technically there would be 365.242 days in a year, when accounting for leap years so: 从技术上讲,一年中有365.242天(考虑leap年),因此:
FLOOR(DATEDIFF(day, @STARTDATE, @ENDDATE) / 365.242)
Should be more correct. 应该更正确。
Test: 测试:
SELECT FLOOR(DATEDIFF(day, '1980-01-16','2015-01-15') / 365.242),
FLOOR(DATEDIFF(day, '1980-01-16','2015-01-16') / 365.242)
ResultSet: 结果集:
--------------------------------------- ---------------------------------------
34 35
Cheers! 干杯!
Count the number of leap days in end_date Deduct number of leap days in start_date. 计算end_date中的leap天数减去start_date中的leap天数。 Deduct the answer from your DATEDIFF. 从您的DATEDIFF中扣除答案。
DECLARE
@START_DATE DATETIME = '2004-02-01',
@END_DATE DATETIME = '2014-01-29'
SELECT (
DATEDIFF(DAY,@START_DATE,@END_DATE)
- (
(CONVERT(INT,@END_DATE - 58) / 1461)
-
(CONVERT(INT,@START_DATE - 58) / 1461)
)
) / 365
-58 to ignore Jan and Feb 1900 -58忽略1900年1月和2月
/ 1461 being the number of days between leap years / 1461是leap年之间的天数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.