How to subtract 2 dates in SQL and get HH:MI:SS
(SQL Server 2005) Iam using MS Access to do this.
Example:
23-09-2013 15:43:59
23-09-2013 15:43:33 -
Wanted answer 00:00:26
How to subtract 2 dates in SQL and get HH:MI:SS
(SQL Server 2005) Iam using MS Access to do this.
Example:
23-09-2013 15:43:59
23-09-2013 15:43:33 -
Wanted answer 00:00:26
Use DateDiff
, for the timespan format use string methods:
SELECT Diff =
right('0'+ rtrim(CAST(DateDiff(hour, @dt2, @dt1) AS VARCHAR(2))), 2) + ':' +
right('0'+ rtrim(CAST(DateDiff(minute, @dt2, @dt1)AS VARCHAR(2))), 2) + ':' +
right('0'+ rtrim(CAST(DateDiff(second, @dt2, @dt1)AS VARCHAR(2))), 2)
If the two dates are in a range of 24 hours you can use this code:
SELECT LEFT(CONVERT(VARCHAR, DATEADD(SECOND, DATEDIFF(SECOND, @Date2, @Date1), 0), 114), 8)
Source: How to convert Seconds to HH:MM:SS using T-SQL
If you can't use native SQL query in your Access program, give a look at these links (Access syntax):
Maybe you can manipulate the resulting string without using CONVERT (not supported in Access).
SELECT Diff = right('0'+ rtrim(CAST(DateDiff(hour, FirstAnswerDate, StartDate)AS VARCHAR(2))), 2) + ':' + right('0'+ rtrim(CAST(DateDiff(minute, FirstAnswerDate, StartDate)AS VARCHAR(2))), 2) + ':' + right('0'+ rtrim(CAST(DateDiff(second, FirstAnswerDate, StartDate)AS VARCHAR(2))), 2) FROM EmergencyCdr WHERE FirstAnswerDate is NOT NULL;
I get this error: Syntax error (Operator is missing) in query expression Diff = ... – Erwin Sep 24 '13 at 10:11