您可以尝试这样的功能:
CREATE FUNCTION GetTimeDifference
(
@FirstDate datetime,
@SecondDate datetime
)
RETURNS varchar(10)
AS
BEGIN
DECLARE @Difference INT
DECLARE @FirstTimeInMin INT
DECLARE @SecondTimeInMin INT
SELECT @FirstTimeInMin =
(DATEPART(hour,@FirstDate) * 60 + DATEPART(minute,@FirstDate))
SELECT @SecondTimeInMin =
(DATEPART(hour,@SecondDate) * 60 + DATEPART(minute,@SecondDate))
IF @FirstTimeInMin = 0
SET @FirstTimeInMin = 24 * 60
IF @SecondTimeInMin = 0
SET @SecondTimeInMin = 24 * 60
SET @Difference = @FirstTimeInMin - @SecondTimeInMin
IF(@Difference < 0)
SET @Difference = @Difference * -1
RETURN RIGHT('0' + CONVERT(varchar(10), @Difference / 60), 2)
+ ':' +
RIGHT('0' + CONVERT(varchar(10), @Difference - (@Difference / 60) * 60 ), 2)
END
GO
你可以像这样使用它:
SELECT dbo.GetTimeDifference('02/02/2012 6:10:00 PM','01/01/2001 12:00:00 AM')
结果应该是 05:50