Difference of two date time in sql server

后端 未结 20 1942
心在旅途
心在旅途 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:37

    For Me This worked Perfectly Convert(varchar(8),DATEADD(SECOND,DATEDIFF(SECOND,LogInTime,LogOutTime),0),114)

    and the Output is HH:MM:SS which is shown accurately in my case.

    0 讨论(0)
  • 2020-12-01 04:38

    Just a caveat to add about DateDiff, it counts the number of times you pass the boundary you specify as your units, so is subject to problems if you are looking for a precise timespan. e.g.

    select datediff (m, '20100131', '20100201')
    

    gives an answer of 1, because it crossed the boundary from January to February, so even though the span is 2 days, datediff would return a value of 1 - it crossed 1 date boundary.

    select datediff(mi, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153')
    

    Gives a value of 1, again, it passed the minute boundary once, so even though it is approx 14 seconds, it would be returned as a single minute when using Minutes as the units.

    0 讨论(0)
  • 2020-12-01 04:38

    Use This for DD:MM:SS:

    SELECT CONVERT(VARCHAR(max), Datediff(dd, '2019-08-14 03:16:51.360', 
             '2019-08-15 05:45:37.610')) 
           + ':' 
           + CONVERT(CHAR(8), Dateadd(s, Datediff(s, '2019-08-14 03:16:51.360', 
             '2019-08-15 05:45:37.610'), '1900-1-1'), 8) 
    
    0 讨论(0)
  • 2020-12-01 04:38

    Check DateDiff out on Books Online.

    0 讨论(0)
  • 2020-12-01 04:39

    Ok we all know the answer involves DATEDIFF(). But that gives you only half the result you may be after. What if you want to get the results in human-readable format, in terms of Minutes and Seconds between two DATETIME values?

    The CONVERT(), DATEADD() and of course DATEDIFF() functions are perfect for a more easily readable result that your clients can use, instead of a number.

    i.e.

    CONVERT(varchar(5), DATEADD(minute, DATEDIFF(MINUTE, date1, date2), 0), 114) 
    

    This will give you something like:

    HH:MM

    If you want more precision, just increase the VARCHAR().

    CONVERT(varchar(12), DATEADD(minute, DATEDIFF(MINUTE, date1, date2), 0), 114) 
    

    HH:MM.SS.MS

    0 讨论(0)
  • 2020-12-01 04:40
    select
    datediff(millisecond,'2010-01-22 15:29:55.090','2010-01-22 15:30:09.153') / 1000.0 as Secs
    
    result:
    Secs
    14.063
    

    Just thought I'd mention it.

    0 讨论(0)
提交回复
热议问题