SQL Server – Calculate Time Difference Between Datetime and Current Date & Time

date formatdatetimesql serversql-server-2008

I would like to calculate the difference between a past datetime and the current datetime with the result in [hh]:mm format.

Best Answer

Try this:

DECLARE @then datetime={ts '2014-01-23 12:34:56.789'};

SELECT LEFT(
    CONVERT(varchar(10), DATEADD(second,
        DATEDIFF(second, @then, GETDATE()),
        {d '1900-01-01'}), 8), 5);

Here's what it does:

  • Calculates the difference in seconds between @then and now (GETDATE())
  • Adds that number of seconds to 1900-01-01
  • Formats the output as hh:mm:ss
  • Returns the first five characters, i.e. hh:mm

Oh, and you can REPLACE the text "00:" with "" (nothing) if you want to hide the hour if it's less than 60 minutes:

SELECT REPLACE(LEFT(CONVERT ....
    ...., 8), 5), '00:', '')