2012-08-27 202 views

回答

4
declare @date1 datetime = '2012-08-04 12:10' 
declare @date2 datetime = '2012-08-04 13:10' 

select cast(@date2 - @date1 as time(0)) 
+1

+1非常好的解決方案! – davek

0

只需減去它們即可獲得日期時間值,然後將其設置爲您想要的格式。

例如

select CONVERT(varchar(100), getdate(), 108) 

在那裏你會用你的減法結果代替getdate()

0

如果經過的時間超過24小時,結果將是誤導(24:00:00的「mod」)。這段代碼將包含天數作爲時間的前綴。我已經包括計算前進和後退間隔。

declare @date1 datetime,@date2 datetime 
set @date1 = '2013-01-02 12:01:02' 
set @date2 = '2013-01-03 22:00:00' 
select 

    -- forward interval 
    case when datediff(dd,@date1,@date2) != 0 then 
    cast(datediff(dd,@date1,@date2) as varchar) 
    + 'd ' + convert(varchar(100), @[email protected], 108) 
    else 
     convert(varchar(100), @[email protected], 108) 
    end as ElapsedT1, 

    -- backward interval 
    case when datediff(dd,@date2,@date1) != 0 then 
    cast(datediff(dd,@date2,@date1) as varchar) 
    + 'd ' + convert(varchar(100), @[email protected], 108) 
    else 
     convert(varchar(100), @[email protected], 108) 
    end as ElapsedT2 

ElapsedT1  ElapsedT2 
1d 14:01:02 -1d 09:58:58 
相關問題