[英]Difference between two dates SQL Server
I'm searching a way to get the difference between two times in SQL Server. 我正在寻找一种方法来获得SQL Server中两次之间的差异。
I would like a format hh:mm:ss
我想要一个格式
hh:mm:ss
Example : 23:00:00 - 18:09:00 = 04:51:00 例如:23:00:00-18:09:00 = 04:51:00
I tried with datediff()
but it only returns hours, minutes or seconds 我尝试使用
datediff()
但它只返回小时,分钟或秒
[EDIT] : [编辑]:
For example : 23:00:00 + 02:00:00 = 01:00:00, how to get 25:00:00? 例如:23:00:00 + 02:00:00 = 01:00:00,如何获得25:00:00?
You can convert to a time: 您可以将时间转换为:
select dateadd(second, datediff(second, date1, date2), cast('0:00:00' as time))
You can then use format()
or convert()
to format the value as a string the way you want. 然后,您可以使用
format()
或convert()
以所需的方式将值格式化为字符串。
Example 例
Declare @T1 time = '23:00'
Declare @T2 time = '18:09'
Select cast(cast(@T1 as datetime) - cast(@T2 as datetime) as time)
Returns 退货
04:51:00.0000000
Or you can use Format() if 2012+ 或者,如果2012+,则可以使用Format()
Select format(cast(@T1 as datetime) - cast(@T2 as datetime),'HH:mm:ss')
Returns 退货
04:51:00
Though Others have already answered correctly. 尽管其他人已经正确回答了。 I would like to add another version.
我想添加另一个版本。
declare @StartTime datetime, @EndTime datetime
select @StartTime = '08:40:18',@EndTime='18:52:48'
select convert(varchar(5),DateDiff(s, @StartTime, @EndTime)/3600)+':'
+ convert(varchar(5),DateDiff(s, @StartTime, @EndTime)%3600/60)+':'
+ convert(varchar(5),(DateDiff(s, @StartTime, @EndTime)%60)) as [hh:mm:ss]
Output: 10:12:30
输出:
10:12:30
: 10:12:30
: 10:12:30
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.