4

我有一个表的两列作为@ABC as DateTime@xyz as DateTime- 数据类型。

我只想减去时间,我正在尝试这样:

对于ABC = 21/02/2012 6:10:00 PMXYZ = 01/01/2001 12:00:00 AM-> 第一行。

CONVERT(varchar(10), dbo.checkingtime.ABC – dbo.checkingtime.XYZ, 108)

我得到的结果是18:10,但我05:50只想要小时和分钟的结果。

可能吗 ?? ?

4

4 回答 4

1

这是你想要的东西。这是内置功能,但我建议您构建自己的功能。

DATEDIFF ( datepart , startdate , enddate )

请注意,您需要在同一天“屏蔽”开始和结束日期以获得您想要的结果(这就是时差)。结果将以分钟为单位,但您可以轻松地将其格式化为小时:分钟。

干杯

于 2013-01-02T08:19:37.920 回答
0

这是我发现的一个很好的例子:

Select start_date, end_date, time_diff,
   EXTRACT(DAY FROM time_diff) days,
   EXTRACT(HOUR FROM time_diff) hours,
   EXTRACT(MINUTE FROM time_diff) minutes,
   EXTRACT(SECOND FROM time_diff) seconds
From
(
Select start_date, end_date, end_date - start_date time_diff
From
(
Select CAST(to_date('21/02/2012 06:10:00 am', 'dd/mm/yyyy  hh:mi:ss am') AS TIMESTAMP)  end_date
 , CAST(to_date('01/01/2012 12:00:00 am', 'dd/mm/yyyy  hh:mi:ss am') AS TIMESTAMP) start_date
From dual
))
/
于 2013-01-02T20:50:01.693 回答
0

这会做,

select right(date2-date1,7) as time from table1

结果:

TIME
5:50AM

SQL_LIVE_DEMO

于 2013-01-02T11:36:35.923 回答
0

您可以尝试这样的功能:

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

于 2013-01-02T09:22:28.857 回答