Calculate time difference in T-SQL / SQL Server

Raymond Tang Raymond Tang 0 1092 0.49 index 6/2/2019

This code snippet shows how to calculate time differences.

In SQL Server, DATEDIFFfunction 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:

Datepart Abbrevations
year yy,yyyy
quarter qq,q
month mm,m
dayofyear dy,y
day dd,d
week wk,ww
hour hh
minute mi,n
second ss,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;
mssql sql-server t-sql

Join the Discussion

View or add your thoughts below

Comments