两个日期之间的持续时间

时间:2011-05-05 07:55:30

标签: sql-server-2005

我需要在两个日期之间以(hh:mm:ss)格式获得持续时间

2011/05/05 11:45:022011/05/01 08:09:57

例如,如果我有这两个日期2011/05/05 01:18:142011/05/05 11:00:00,则结果为:02:18:14

3 个答案:

答案 0 :(得分:3)

DECLARE @dt1 datetime

DECLARE @dt2 datetime

SELECT @dt1 = '2011-05-05 11:45:02', @dt2 = '2011-05-05 08:09:57'

SELECT CONVERT(VARCHAR(8),@dt1-@dt2,108)


-- RESULT IS : 03:35:05

答案 1 :(得分:0)

据我所知,SQL(或TSQL)中没有DATETIME_INTERVAL数据类型,因此您必须手动格式化DATEDIFF函数的结果。

 declare @hours as int
 declare @minutes as int
 declare @seconds as int
 declare @time_interval as nvarchar(10)

 set @hours =  DATEDIFF(ss,'2011/05/05 01:18:14', '2011/05/05 11:00:00') / 3600
 set @minutes = (DATEDIFF(ss,'2011/05/05 01:18:14', '2011/05/05 11:00:00') - @hours*3600)/60
 set @seconds = DATEDIFF(ss,'2011/05/05 01:18:14', '2011/05/05 11:00:00') - @hours*3600 - @minutes * 60

 set @time_interval = (cast(@hours as nvarchar) +':'+ cast(@minutes as nvarchar)+':'+ cast(@seconds as nvarchar))

print @time_interval

答案 2 :(得分:0)

试试这个:

declare @date1 datetime='2011/05/05 01:18:14', @date2 datetime='2011/05/05 11:00:00'
select CAST((@date2-@date1) as time(0))

这是声明中元素的重要顺序。在其他情况下,你将得到24小时 - 你的时间。