Calculate time difference in T-SQL / SQL Server

Raymond Raymond event 2019-11-18 visibility 1,009
more_vert

This code snippet shows how to calculate time differences.

In SQL Server, DATEDIFF function can be used to find the differences between two dates/timestamps.

The syntax is:

DATEDIFF ( datepart , startdate , enddate )  

For parameter datepart, refer to the following table:

DatepartAbbrevations
yearyy,yyyy
quarterqq,q
monthmm,m
dayofyeardy,y
daydd,d
weekwk,ww
hourhh
minutemi,n
secondss,s
millisecond
ms
microsecond
mcs
nanosecond
ns

Code snippet

SELECT DATEDIFF(m,CAST('20171015' AS DATE), CAST('20191015' AS DATE)) AS Diff_Months;
SELECT DATEDIFF(d,CAST('20171015' AS DATE), CAST('20191015' AS DATE)) AS Diff_Days;
SELECT DATEDIFF(ww,CAST('20171015' AS DATE), CAST('20191015' AS DATE)) AS Diff_Weeks;
SELECT DATEDIFF(HH,CAST('20171015' AS DATE), CAST('20191015' AS DATE)) AS Diff_Hours;
More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts