如何获取SQL Server中两个日期之间的总小时数? [英] How to get total number of hours between two dates in sql server?

查看:684
本文介绍了如何获取SQL Server中两个日期之间的总小时数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑两个日期 2010-03-18 22:30:45 2010-03-19 03:30:15 ....如何获取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.....

推荐答案

@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

这篇关于如何获取SQL Server中两个日期之间的总小时数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆