By using this site, you acknowledge that you have read and understand our Cookie policy, Privacy policy and Terms .

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;
info Last modified by Raymond at 10 months ago * This page is subject to Site terms.

More from Kontext

local_offer mssql local_offer t-sql

visibility 10
thumb_up 0
access_time 5 months ago

This code snippet shows how to convert string to date.

open_in_new View open_in_new Code snippets

local_offer mssql local_offer t-sql

visibility 11
thumb_up 0
access_time 5 months ago

JSON is commonly used in modern applications for data storage and transfers. Pretty much all programming languages provide APIs to parse JSON. 

open_in_new View open_in_new Code snippets

local_offer mssql local_offer t-sql

visibility 12
thumb_up 0
access_time 5 months ago

In Oracle database, you can select from dual table if you only want to return a one row result set. In many other databases, the query engine supports select directly from constant values without specifying a table name. 

open_in_new View open_in_new Code snippets

local_offer mssql local_offer t-sql

visibility 30
thumb_up 2
access_time 5 months ago

In different databases, the syntax of selecting top N records are slightly different. They may also differ from ISO standards.

open_in_new View open_in_new Code snippets

info About author

Kontext dark theme mode

Dark theme mode

Dark theme mode is available on Kontext.

Learn more arrow_forward
Kontext Column

Kontext Column

Created for everyone to publish data, programming and cloud related articles. Follow three steps to create your columns.

Learn more arrow_forward
info Follow us on Twitter to get the latest article updates. Follow us