我需要得到两个日期之间的结果如下:
DATE_START = 01/01/2010
DATE_END = 2012年10月21日
结果:1年9个月20天。
我试过代码波纹管,但没有奏效。 它有时会返回负日期:
SELECT CAST(DATEDIFF(yy, date_start, date_end) AS varchar(4)) +' year '+
CAST(DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy,date_start , date_end), date_start), date_end) AS varchar(2)) +' month '+
CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, date_start, date_end), date_start), date_end), DATEADD(yy, DATEDIFF(yy, date_start, date_end), date_start)), date_end) AS varchar(2)) +' day' AS result
谢谢!
这也许不能正确处理闰年如果@s
或@e
相邻他们,但除此之外,这应该是八九不离十:
DECLARE @s DATE, @e DATE
SELECT @s = '20100101', @e = '20121021';
SELECT y + ' year(s), ' + m + ' month(s) and ' + d + ' day(s).'
FROM
(
SELECT
RTRIM(y),
RTRIM(m - CASE WHEN pd < 0 THEN 1 ELSE 0 END),
RTRIM(CASE WHEN pd < 0 THEN nd ELSE pd END)
FROM
(
SELECT
DATEDIFF(MONTH, @s, @e) / 12,
DATEDIFF(MONTH, @s, @e) % 12,
DATEDIFF(DAY, @s, DATEADD(MONTH, -DATEDIFF(MONTH, @s, @e), @e)),
DATEDIFF(DAY, @s, DATEADD(MONTH, 1-DATEDIFF(MONTH, @s, @e), @e))
) AS x (y, m, pd, nd)
) AS y (y, m, d);
输出:
2 year(s), 9 month(s) and 20 day(s).
如果占额外的一天闰年是至关重要的,我敢肯定,它可以进行调整,以处理这个问题。 虽然通过最小的测试中,我没能看到它会打破任何情况下(它只是不觉得它应该工作)。
尝试这个
DECLARE @months decimal (5,2)
SELECT @months = DATEDIFF(month, '01/22/2010','10/21/2012')/12.0
;WITH CTE AS
(
SELECT FLOOR(@months) AS years,(@months-FLOOR(@months)) * 12 AS months
)
SELECT years, CAST(months as int) months,
case when day('01/22/2010') > day('10/21/2012')
then day('10/21/2012') +
datediff(day,'01/22/2010',dateadd(month,datediff(month,0,'01/22/2010')+1,0))- 1
ELSE day('10/21/2012')-day('01/22/2010') end
from cte
您可以使用的功能也看到这样得到的时间差http://atikpassion.blogspot.com/2014/01/get-difference-between-two-dates-in.html