Difference of two date time in SQL Server
The DATEDIFF function in SQL Server enables swift calculation of time differences. You just need to indicate the unit (e.g., year, quarter, month, day, hour, minute, second, millisecond), and the start and end date-times:
Remember, DATEDIFF counts only completed units between the two dates.
Defusing the "millisecond" bomb
If you need exact precision down to the millisecond, switch the DATEDIFF unit to millisecond
:
For differences in seconds to ensure perfect precision, divide the result by 1000:
Time-lapse from the present
To calculate the difference between a specific date-time and the current datetime, utilize the GETDATE() function:
Face-off: DATEDIFF vs DATEADD
Suppose you need to adjust the date to the beginning of the hour before comparison. First, normalize the date using DATEADD, then apply DATEDIFF:
Pimp my output
The CONVERT function helps to format date differences in an eye-pleasing, human-readable way:
Multi-zone wrestling
Do not forget about time zones when calculating across them. Use AT TIME ZONE to account for time zone differences:
Overloading the SELECT
You can stack the DATEDIFF within a single SELECT statement to execute multiple time calculations:
Gotcha! Boundary crossing
BOUNDARY CROSSING is important to consider when using DATEDIFF. This function counts the number of boundaries crossed, not the time elapsed.
Leap seconds: The unseen enemies
SQL Server ignores leap seconds. Keep that in mind, or your calculations risking being "leap seconds" off.
Level-up: Advanced learning
Explore Microsoft Learn and MSDN documentation for a deep dive into the functionalities of datetime in SQL Server.
Was this article helpful?