Calculate time difference in T-SQL / SQL Server

event 2019-11-18 visibility 959 comment 0 insights
more_vert
insights Stats
Raymond Raymond Code Snippets & Tips

Code snippets and tips for various programming languages/frameworks. All code examples are under MIT or Apache 2.0 license unless specified otherwise. 

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