Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating timespan with t-sql

Given two date/times:

@start_date = '2009-04-15 10:24:00.000' @end_date = '2009-04-16 19:43:01.000' 

Is it possible to calculate the time elapsed between the two dates in the following format

1d 9h 19m

like image 864
jdiaz Avatar asked Apr 17 '09 03:04

jdiaz


People also ask

How do I get TimeSpan in SQL Server?

This should do the trick: SELECT CAST(DATEDIFF(second, \@start_date, \@end_date) / 3600 AS varchar(max)) + ':' + RIGHT('0' + CAST(DATEDIFF(second, \@start_date, \@end_date) % 3600 / 60 AS varchar(2)), 2) + ':' + RIGHT('0' + CAST(DATEDIFF(second, \@start_date, \@end_date) % 60 AS varchar(2)), 2) - bah, does anybody know ...

How do you find time intervals in SQL?

MySQL TIMEDIFF() Function The TIMEDIFF() function returns the difference between two time/datetime expressions. Note: time1 and time2 should be in the same format, and the calculation is time1 - time2.

How is duration calculated in SQL Server?

If you can tolerate the 3.3ms accuracy and rounding provided by the DATETIME data-type, the duration calculation is incredibly simple. Just subtract the start date and time from the end date and time.


1 Answers

You can get the difference between the two dates to whatever resolution you want (in your example, minutes):

DATEDIFF(minute, @start_date, @end_date) 

From there it's a simple matter of dividing minutes into hours and hours into days and modding the remainder.

like image 66
Rex M Avatar answered Oct 04 '22 12:10

Rex M