Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show datediff as seconds, milliseconds

Tags:

I'm trying to calculate the difference between two datetime values.

I tried datediff(s, begin,end) and datediff(ms, begin,end) however I want the difference to be returned as seconds,milliseconds like the following:

4,14 63,54 
like image 450
Pieter_Daems Avatar asked Mar 27 '13 13:03

Pieter_Daems


People also ask

How do I get time difference between seconds in SQL?

To calculate the difference between the timestamps in MySQL, use the TIMESTAMPDIFF(unit, start, end) function. The unit argument can be MICROSECOND , SECOND , MINUTE , HOUR , DAY , WEEK , MONTH , QUARTER , or YEAR . To get the difference in seconds as we have done here, choose SECOND .

What does datediff return?

The DATEDIFF() function returns the difference between two dates.

How do you use datediff?

To calculate the number of days between date1 and date2, you can use either Day of year ("y") or Day ("d"). When interval is Weekday ("w"), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1.

How does datediff work in SQL?

The DATEDIFF() function returns an integer value that represents the difference between the start date and end date, with the date part as the unit. If the result is out of range for the integer (-2,147,483,647), the DATEDIFF() function returns an error. Here, the DATEDIFF BIG() function should be used instead.


2 Answers

SELECT    DATEDIFF(MILLISECOND, begin, end) / 1000,    DATEDIFF(MILLISECOND, begin, end) % 1000 FROM ...; 

If you absolutely must form it as a string in your SQL query (can't your presentation tier do that?), then:

SELECT    CONVERT(VARCHAR(12),  DATEDIFF(MILLISECOND, begin, end) / 1000)   + ','    + RIGHT('000' + CONVERT(VARCHAR(4), DATEDIFF(MILLISECOND, begin, end) % 1000), 3) FROM ...; 

Also I really hope you have better column names than begin and end.

like image 197
Aaron Bertrand Avatar answered Oct 18 '22 21:10

Aaron Bertrand


Actually, the marked answer originally produced wrong results for milliseconds 1 - 99:

Example 1 second, 27 milliseconds:

  1. DATEDIFF % 1000 will return 27
  2. CONVERT will convert to '27'
  3. String concatenation will build '1' + ',' + '27'
  4. Result: '1.27' which means 270ms rather than 27ms

Don't forget to pad the milliseconds to three zeros:

DECLARE @start datetime2(7) = '2015-07-03 09:24:33.000' DECLARE @end datetime2(7) = '2015-07-03 09:24:34.027'  SELECT      CAST (DATEDIFF(SECOND, @start, @end) AS nvarchar(3)) + N'.' +     RIGHT('000' + CAST((DATEDIFF(MILLISECOND, @start, @end) % 1000) AS nvarchar(3)), 3) 
like image 34
Wolfgang Avatar answered Oct 18 '22 23:10

Wolfgang