SQL Server – Calculate Hour, Minute, and Second Difference Between Datetimes

datedatetimesql serversql-server-2012

The table Task has columns as:

Task(TaskID, TaskName, CreatedDate)

And want to execute code block based on datetime difference as:

IF Task CreatedDate has passed 15 Minute THEN

Execute block #01

ELSE IF Task CreatedDate has not passed 15 Minute yet THEN

Execute block #02

I tested below query but it gives result as 61633440

SELECT DATEDIFF(MINUTE, CONVERT(VARCHAR(10), CreatedDate, 108), CURRENT_TIMESTAMP) AS MinuteDiff

How could we achieve above in sql?

Best Answer

CURRENT_TIMESTAMP returns the current datetime something like 2017-03-09 15:19:53.770.

CONVERT(VARCHAR(10), CreatedDate, 108) returns a string with only time 15:19:53.

The second parameter of DATEDIFF takes a datetime so your string is implicitly converted to a datetime. In lack of something better to use for a date SQL Server uses 1900-01-01 so your second parameter ends up to be 1900-01-01 15:19:53.000 and the function returns the number of minutes since the beginning of the previous century.

Remove the convert in the second parameter and it should work just fine for you.