且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取SQL Server中两个日期之间的总小时数?

更新时间:2023-01-30 10:50:48

@codeka回答了小时部分(来自标题),但在您的问题正文中,您要求小时和分钟,因此,这是一种方法

@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

这在第一部分中的作用是@codeka显示的内容。它为您提供了两个小时之间的实际全时差。 sql中的第二项以分钟为单位(第一个日期+经过的小时数)和第二个日期之间的日期差。您必须从分钟部分的等式中消除小时,否则您将获得日期之间的实际分钟。可以在这里研究Datediff及其允许的Datepart标识符:

http ://msdn.microsoft.com/zh-CN/library/ms189794.aspx

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