(Transact-SQL)DATEDIFF和闰年

时间:2014-08-29 10:03:10

标签: sql sql-server tsql

我的DATEDIFF功能有问题。

我的日期格式为dd/mm/yyyy

@START_DATE = 01/02/2004
@END_DATE = 29/01/2014

查询(DATEDIFF(DAY,@START_DATE,@END_DATE) / 365)返回10,但正确年份的数量为9。发生这种情况是因为我的查询没有考虑闰年。


我能做些什么来保持准确的计数? 感谢。

4 个答案:

答案 0 :(得分:1)

您可以创建一个函数来解决:

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

同时检查this

答案 1 :(得分:1)

从技术上讲,一年中会有365.242天,因为会计闰年所以:

FLOOR(DATEDIFF(day, @STARTDATE, @ENDDATE) / 365.242)

应该更正确。

测试:

SELECT  FLOOR(DATEDIFF(day, '1980-01-16','2015-01-15') / 365.242),
        FLOOR(DATEDIFF(day, '1980-01-16','2015-01-16') / 365.242)

结果集:

--------------------------------------- ---------------------------------------
34                                      35

干杯!

答案 2 :(得分:0)

我相信以下逻辑符合您的要求:

   datediff(year,
            @START_DATE - datepart(dayofyear, @START_DATE) + 1,
            @END_DATE - datepart(dayofyear, @START_DATE) + 1
           ) as d2

注意:这会将该日期视为datetime,因为算术更容易表达。你也可以这样写:

   datediff(year,
            dateadd(day, - datepart(dayofyear, @START_DATE) + 1, @START_DATE),
            dateadd(day, - datepart(dayofyear, @START_DATE) + 1, @END_DATE)
           ) as d2

以下查询是演示:

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

答案 3 :(得分:0)

在start_date中计算end_date中的闰天数减去start_date中的闰天数。从您的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忽略1900年1月和2月

/ 1461是闰年之间的天数