I want Hours,Min, second difference from two datetime
I came across an easier way of solving this issue.
First, a quick example of turning a "number of seconds" into the "hh:mm:ss" format.
DECLARE @NumberOfSeconds int
SET @NumberOfSeconds = 3843 -- 1 hour, 4 minutes, 3 seconds
SELECT @NumberOfSeconds AS 'seconds',
CONVERT(varchar, DATEADD(second, @NumberOfSeconds, 0), 108) AS 'hh:mm:ss'
This will give us this output:
And we can easily take this a step further, calculate the number of seconds between two datetimes, and display it in hh:mm:ss
format:
DECLARE
@NumberOfSeconds int,
@StartTime datetime = '2017-09-14 14:16:11',
@EndTime datetime = '2017-09-14 14:23:13'
SET @NumberOfSeconds = DATEDIFF(second, @StartTime, @EndTime)
SELECT @NumberOfSeconds AS 'seconds',
CONVERT(varchar, DATEADD(second, @NumberOfSeconds, 0), 108) AS 'hh:mm:ss'
Which gives us this output:
Simple, hey ?
(And yes, you can simplify it further by putting the DATEDIFF
directly into the DATEADD
function.)
You can do it in a very simple way:
declare @date1 datetime, @date2 datetime
set @date1=DATEADD(s,-638,getdate())
set @date2=GETDATE()
select convert(char(8),dateadd(s,datediff(s,@date1,@date2),'1900-1-1'),8)
... the result is 00:10:38 (638s = 600s + 38s = 10 minutes and 38 seconds)
Another example:
select distinct convert(char(8),dateadd(s,datediff(s, CRDATE , GETDATE() ),'1900-1-1'),8) from sysobjects order by 1
It will works until the difference of 86399 seconds (23:59:59):
select convert(char(8),dateadd(s,datediff(s
, DATEADD(s,-86399,GETDATE())
, GETDATE()
),'1900-1-1'),8)
... after that it will return to zero:
select convert(char(8),dateadd(s,datediff(s
, DATEADD(s,-86400,GETDATE())
, GETDATE()
),'1900-1-1'),8)