Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get total number of hours between two dates in sql server?

Consider two dates 2010-03-18 22:30:45 and 2010-03-19 03:30:15 .... How to get the number of hours and minutes in between the two dates in sql server.....

like image 705
ACP Avatar asked Mar 19 '10 05:03

ACP


People also ask

How do I calculate the number of hours between two dates in SQL?

DATEDIFF(hour, start_date, end_date) will give you the number of hour boundaries crossed between start_date and end_date .

How do you sum HH MM SS in SQL Server?

Answers. Just sum the seconds first and do the formatting later: WITH Summed AS ( SELECT S.name , SUM(DATEDIFF(SECOND, T. create_date, T.

How do you calculate time difference between days hours and minutes in SQL Server?

To calculate the difference between the arrival and the departure in T-SQL, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument can be microsecond , second , minute , hour , day , week , month , quarter , or year .


1 Answers

@codeka answered with the hours part (from your title) but in the body of your question you asked for hours and minutes so, here is one way

 select DATEDIFF(hh, @date1, @date2) as Hours_Difference,   
    DATEDIFF(mi,DATEADD(hh,DATEDIFF(hh, @date1, @date2),@date1),@date2) as Minutes_Difference

What this does in the first part is what @codeka showed. It gives you the datediff between the two dates in actual full hours. The second term in the sql gives the datediff in minutes between the (first date + the hours elapsed) and the second date. You have to eliminate the hours from the equation in the minutes part or you will get the actual minutes between the dates. Datediff and its allowed Datepart identifiers can be researched here:
http://msdn.microsoft.com/en-us/library/ms189794.aspx

like image 117
William Salzman Avatar answered Oct 22 '22 11:10

William Salzman