user6558380
user6558380

Reputation:

SQL difference between dates(year,month,day)

I have a problem getting difference between two dates in years, months, days without using function, just the Select statement.

So far i have this messy code, but it doesnt work so well, as sometimes the month/day is - . tblProject.BillingDate is StartDate, tblServiceTicket.ServiceTicketDate is EndDate.

         CONVERT(varchar(12),datediff(YEAR,tblProject.BillingDate,tblServiceTicket.ServiceTicketDate))  + ' year, '
        + CONVERT(varchar(12),DATEDIFF(MM, DATEADD(YY, datediff(YEAR,tblServiceTicket.ServiceTicketDate,tblProject.BillingDate), tblServiceTicket.ServiceTicketDate), tblProject.BillingDate)) + ' months, '
        + CONVERT(varchar(12),DATEDIFF(DD, DATEADD(MM, DATEDIFF(MM, DATEADD(YY, (datediff(YEAR,tblProject.BillingDate,tblServiceTicket.ServiceTicketDate)), tblProject.BillingDate), tblServiceTicket.ServiceTicketDate), DATEADD(YEAR, datediff(YEAR,tblProject.BillingDate,tblServiceTicket.ServiceTicketDate) , tblProject.BillingDate)), tblServiceTicket.ServiceTicketDate)) + ' days '

Upvotes: 0

Views: 404

Answers (1)

Laughing Vergil
Laughing Vergil

Reputation: 3756

The only way that I know to do this is semi-iteratively, like this. This version can be improved with coding around DATEDIFF, but it shows the logic needed more clearly than the DATEDIFF version.

DECLARE @dstart datetime, 
    @dend datetime,
    @dwork datetime

DECLARE @yy int, 
    @mm int, 
    @dd int

SET @dstart = '19570125'
SET @dend = '20161214'

DECLARE @ix int

-- Get Year interval
SET @ix = 0
WHILE @ix >= 0
BEGIN
    Set @ix = @ix + 1
    IF Dateadd(year, @ix, @dstart) > @dend
    BEGIN
        SET @yy = @ix - 1
        SET @ix = -1
    END
END

Set @dwork = Dateadd(year, @yy, @dstart)

-- Get month interval
SET @ix = 0
WHILE @ix >= 0
BEGIN
    Set @ix = @ix + 1
    IF Dateadd(MONTH, @ix, @dwork) > @dend
    BEGIN
        SET @mm = @ix - 1
        SET @ix = -1
    END
END

Set @dd = DATEDIFF(day, dateadd(month, @mm, @dwork), @dend)

SELECT 'The difference is ' + Cast(@yy as varchar) + ' years, ' + Cast(@mm as varchar) + ' Months, and ' + Cast(@dd as varchar) + ' Days'

Here are some sample outputs, showing how it handles a couple of problem cases.

-- One day at new years
SET @dstart = '20161231'
SET @dend = '20170101'

-- The difference is 0 years, 0 Months, and 1 Days

-- One month to a shorter month
SET @dstart = '20160131'
SET @dend = '20170228'

-- The difference is 1 years, 1 Months, and 0 Days

-- My age
SET @dstart = '19570125'
SET @dend = '20161214'

-- The difference is 59 years, 10 Months, and 19 Days

Upvotes: 1

Related Questions