Search This Blog

Thursday, January 16, 2014

Duration between two dates in SQL Server example

SQL Server > Built-In Functions > DATEDIFF

Returns the number of date and time boundaries crossed between two specified dates.

Example:

Duration between two dates in SQL Server example

DECLARE 
  @date1 DATETIME
,@date2   DATETIME

SELECT
  @date1 = getdate(),
   @date2  = dateadd(day,1,getdate()),
  @date2  = dateadd(minute,5,@date2)

SELECT
  @date1,
  @date2,
  DATEDIFF(hh, @date1, @date2) as Hours,  
  DATEDIFF(mi,DATEADD(hh,DATEDIFF(hh, @date1, @date2),@date1),@date2) as Minutes

Result: