简体   繁体   English

获得两个日期之间的小时数差异

[英]Get difference in hours between two dates

How can I subtract two dates ( entry_date from status_change_date ) to get hours between them? 如何减去两个日期( status_change_date entry_date )以获取两个小时之间的小时数? I do this based on an IF statement where both dates are in YYYY,MM,DD 12:00:00 format 我基于两个日期均为YYYY,MM,DD 12:00:00格式的IF语句来执行此操作

(IF Invoice_Num != next Inv_Num then entry_date - status_change_date else... 

It returns an answer in days instead of hours. 它以天而不是小时为单位返回答案。 I also tried using minutes(entry_day) and hours(status_change_date) in Crystal after the code was done, but I still got day values. 在代码完成之后,我还尝试在Crystal中使用minutes(entry_day)hours(status_change_date) ,但仍然有day值。

declare @startDate datetime
declare @endDate datetime

set @startDate = '2016-12-05 08:05:00';
set @endDate = '2016-12-05 09:52:00';

select CONVERT(varchar(3),DATEDIFF(minute,@startDate, @endDate)/60) + ':' +
          RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,@startDate,@endDate)%60),2)
          as TotalHours

Check this example, get the hours and minutes between to datetime vars 检查此示例,获取日期时间变量之间的小时和分钟

From document TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2) , 从文档TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)中

SELECT TIMESTAMPDIFF(HOUR, '2016-12-05 12:00:00', '2016-12-06 12:00:00');

This will get you 24 hours. 这将为您提供24小时的服务。

SQLFiddle Demo SQLFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM