查找2个日期之间的天数,月数和年数

时间:2016-10-05 07:37:57

标签: tsql sql-server-2012

我想要获得数年,数月而不是。两个日期之间的天数。 但是当日期如下所示时,它会给出错误的输出(FromDate的月份部分大于Todate)。

declare @FromDate date='2010-10-27'
declare @Todate date='2012-03-02'

SELECT
DATEDIFF( mm, @FromDate, @ToDate) / 12 AS years
, datediff(mm,@FromDate, @ToDate)  % 12  AS months
, DATEDIFF( dd, DATEADD( mm, DATEDIFF( mm, @FromDate, @ToDate), @FromDate), @ToDate) as Days


**It Shows Output as**
Years Months  days
1      5      -25

应该是4个月和29天。请告诉我如何获得所需的输出。 在此先感谢

3 个答案:

答案 0 :(得分:0)

以下可能会解决问题 - 但我认为,正确的值将是1年,4个月和4天!?

declare @start date = '2010-10-27'
declare @ende date = '2012-03-02'


SELECT DATEDIFF(mm, @start, @ende)/12 MyYears
      ,(DATEDIFF(mm, @start, @ende)%12)-1 MyMonths
      ,DATEDIFF(dd, DATEADD(mm, (DATEDIFF(mm, @start, @ende)%12)-1,DATEADD(yy, DATEDIFF(mm, @start, @ende)/12, @Start)), @Ende) MyDays

--Check of result
SELECT dateadd(dd, 4, dateadd(mm, 4, dateadd(yy, 1, @start))) x

答案 1 :(得分:0)

我用过这个。这给出了期望的结果。

 (@FromDate date,
    @ToDate Date  
    )



DECLARE @Years INT, @Months INT, @Days INT

 SET @Years = DATEDIFF(YEAR, @FromDate, @ToDate)
   IF DATEADD(YY, @Years, @FromDate) > @ToDate
    BEGIN
        SET @Years = @Years - 1
    END

SET @FromDate = DATEADD(YY, @Years, @FromDate)
SET @Months = DATEDIFF(MM, @FromDate, @ToDate)

IF DATEADD(MM, @Months, @FromDate) > @ToDate
BEGIN
    SET @Months = @Months - 1
END

SET @FromDate = DATEADD(MM, @Months, @FromDate)
SET @Days = DATEDIFF(DD, @FromDate, @ToDate)


 Select @Years as Years,@Months as Months,
             @Days as Days

答案 2 :(得分:-1)

也许这是正确的

声明@FromDate date ='2010-10-27' 声明@Todate date ='2012-03-02'

选择 DATEDIFF(yy,@ FromDate,@ Todate)AS年, DATEDIFF(mm,@ FromDate,@ Todate)作为月, DATEDIFF(dd,@ FromDate,@ Todate)AS DAYS