Question

i have a query that uses DateDiff function of the SQL.The interval returns min, hour or days according to how i put it. I want to return a Datetime datatype instead of the resulting integer type as it does. I tried to cast it as follows .

 DATEDIFF(cast(MIN as datetime), b.FollowUpTime, a.FollowUpTime) 

This returns an error. I also tried

DATEDIFF(Convert(datetime,convert(char(8),MiNUTE)), b.FollowUpTime, a.FollowUpTime)

It also returns wrong parameter error. Any help would be appreciated . Thanks

Was it helpful?

Solution

You can use this to find the difference between two dates:

SELECT 
    convert(VARCHAR, abs(datediff(second, @date1, @date2) / 60 / 60 / 24)) 
    + ':' + 
    convert(VARCHAR, abs(((datediff(second, @date1, @date2) / 60) / 60) % 24)) 
    + ':' + 
    convert(VARCHAR, abs((datediff(second, @date1, @date2) / 60) % 60)) 
    + ':' + 
    convert(VARCHAR, abs((datediff(second, @date1, @date2) % 60)))

You'll just have to change the @date1 and @date2 with the dates you need.

Here is a SQLFiddle where you can test this out.

If you really want to convert to datetime, use this:

SELECT 
    convert(DATETIME, 
        (convert(VARCHAR, abs(((datediff(second, @date1, @date2) / 60) / 60) % 24)) 
         + ':' + 
        convert(VARCHAR, abs((datediff(second, @date1, @date2) / 60) % 60)) 
         + ':' + 
        convert(VARCHAR, abs((datediff(second, @date1, @date2) % 60)))
           ) 
   + dateadd(day, 
             abs(datediff(second, @date1, @date2) / 60 / 60 / 24), 
             '01-01-1900 00:00:00')
             )

Here is a SQLFiddle for the second query

OTHER TIPS

As pointed out in the comments DATEDIFF returns an INT value of the difference of both dates.

Since DATETIME is based on 1900-01-01 being the "base date" meaning assinging 0 to a DATETIME will result in the value 1900-01-01, you can add your date difference to that and get a value relative to that point in time (1900-01-01).

Here is an example:

DECLARE @date1 DATETIME = GETUTCDATE()
DECLARE @date2 DATETIME = DATEADD(DAY, -1, GETUTCDATE())

DECLARE @zeroDate DATETIME = 0

SELECT DATEADD(SECOND, DATEDIFF(SECOND, @date1, @date2), @zeroDate)

I also set up an SQLFiddle where you can try that out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top