I need to get the following result between two dates:
date_start = 01/01/2010
date_end = 10/21/2012
result: 1 year, 9 months and 20 days.
I tried the code bellow, but it didn't work. It returns negative dates sometimes:
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
Thank You!
you can get date difference using function also see this http://atikpassion.blogspot.com/2014/01/get-difference-between-two-dates-in.html
This may not correctly handle leap years if
@s
or@e
are adjacent to them, but other than that this should be pretty close:Output:
If accounting for the extra day in a leap year is crucial, I'm sure it could be adjusted to handle that. Though through minimal testing I wasn't able to see any case where it would break (it just doesn't feel like it should work).
Try this