DECLARE @date1 DATETIME, @date2 DATETIME
DECLARE @result VARCHAR(100)
DECLARE @years BIGINT, @months BIGINT, @weeks BIGINT, @days BIGINT, @hours BIGINT, @minutes BIGINT
DECLARE @KEEP DATETIME
SET @date1 = '20130829 13:48:35.710'
SET @date2 = '20130903 17:04:27.493'
if @date1>@date2
begin
SET @[email protected]
SET @[email protected]
SET @[email protected]
end
Select @years=DATEDIFF(yy,@date1,@date2)
if DateAdd(yy,[email protected],@date2)<@date1 Select @[email protected]
Set @date2= DateAdd(yy,[email protected],@date2)
Select @months=DATEDIFF(mm,@date1,@date2)
if DateAdd(mm,[email protected],@date2)<@date1 Select @[email protected]
Set @date2= DateAdd(mm,[email protected],@date2)
Select @weeks=DATEDIFF(wk,@date1,@date2)
if DateAdd(wk,[email protected],@date2)<@date1 Select @[email protected]
Set @date2= DateAdd(wk,[email protected],@date2)
Select @days=DATEDIFF(dd,@date1,@date2)
if DateAdd(dd,[email protected],@date2)<@date1 Select @[email protected]
Set @date2= DateAdd(dd,[email protected],@date2)
Select @hours=DATEDIFF(hh,@date1,@date2)
if DateAdd(hh,[email protected],@date2)<@date1 Select @[email protected]
Set @date2= DateAdd(hh,[email protected],@date2)
Select @minutes=DATEDIFF(mi,@date1,@date2)
Select @result= ISNULL(CAST(NULLIF(@years,0) as varchar(10)) + ' Years','')
+ ISNULL(' ' + CAST(NULLIF(@months,0) as varchar(10)) + ' Months','')
+ ISNULL(' ' + CAST(NULLIF(@weeks,0) as varchar(10)) + ' Weeks','')
+ ISNULL(' ' + CAST(NULLIF(@days,0) as varchar(10)) + ' Days','')
+ ISNULL(' ' + CAST(NULLIF(@hours,0) as varchar(10)) + ' Hours','')
+ ISNULL(' ' + CAST(@minutes as varchar(10)) + ' Minutes','')
Select @result
-- OUTPUT : 5 Days 3 Hours 16 Minutes
確定分鐘(或小時)的時間差僅然後用數學的方法計算的其餘部分(每小時60分鐘,每天1440分鐘,每週10080分鐘等),從總分鐘減去當你去時。您可能還需要考慮閏年,但如果正確完成,它是一個可行且準確的選項。 – user3004228
呃,沒有。 4個月=多少個小時?使用內置的日期操作,而不是編寫在DST,閏年和閏秒上失敗的糟糕的日期操作。 – Anon