Difference of two date time in sql server

后端 未结 20 2039
心在旅途
心在旅途 2020-12-01 03:53

Is there any way to take the difference between two datetime in sql server?

For example, my dates are

  1. 2010-01-22 15:29:55.090
20条回答
  •  执笔经年
    2020-12-01 04:48

    I can mention four important functions of MS SQL Server that can be very useful:

    1) The function DATEDIFF() is responsible to calculate differences between two dates, the result could be "year quarter month dayofyear day week hour minute second millisecond microsecond nanosecond", specified on the first parameter (datepart):

    select datediff(day,'1997-10-07','2011-09-11')
    

    2) You can use the function GETDATE() to get the actual time and calculate differences of some date and actual date:

    select datediff(day,'1997-10-07', getdate() )
    

    3) Another important function is DATEADD(), used to convert some value in datetime using the same datepart of the datediff, that you can add (with positive values) or substract (with negative values) to one base date:

    select DATEADD(day,  45, getdate()) -- actual datetime adding 45 days
    select DATEADD(  s,-638, getdate()) -- actual datetime subtracting 10 minutes and 38 seconds
    

    4) The function CONVERT() was made to format the date like you need, it is not parametric function, but you can use part of the result to format the result like you need:

    select convert(  char(8), getdate() ,   8) -- part hh:mm:ss of actual datetime
    select convert(  varchar, getdate() , 112) -- yyyymmdd
    select convert( char(10), getdate() ,  20) -- yyyy-mm-dd limited by 10 characters
    

    DATETIME cold be calculated in seconds and one interesting result mixing these four function is to show a formated difference um hours, minutes and seconds (hh:mm:ss) between two dates:

    declare  @date1 datetime, @date2 datetime
    set @date1=DATEADD(s,-638,getdate())
    set @date2=GETDATE()
    
    select convert(char(8),dateadd(s,datediff(s,@date1,@date2),'1900-1-1'),8)
    

    ... the result is 00:10:38 (638s = 600s + 38s = 10 minutes and 38 seconds)

    Another example:

    select distinct convert(char(8),dateadd(s,datediff(s, CRDATE , GETDATE() ),'1900-1-1'),8) from sysobjects order by 1
    

提交回复
热议问题