jdi*_*iaz 43 t-sql sql-server-2005
给出两个日期/时间:
@start_date = '2009-04-15 10:24:00.000'
@end_date = '2009-04-16 19:43:01.000'
Run Code Online (Sandbox Code Playgroud)
是否可以按以下格式计算两个日期之间的时间
1d 9h 19m
Rex*_*x M 71
您可以将两个日期之间的差异变为您想要的任何分辨率(在您的示例中为分钟):
DATEDIFF(minute, @start_date, @end_date)
Run Code Online (Sandbox Code Playgroud)
从那里可以很简单地将分钟分成几小时和几小时到几天,并修改其余部分.
小智 27
我知道这个帖子比较老,原来的参与者可能不再看了,但我偶然发现了它,并且最近已经编写了一些代码来做一些非常接近jdiaz请求的代码.结果呈现为D:H:M:S格式的字符串.
第一步是以秒为单位获得时间跨度:
DECLARE @ElapsedS INT
SET @ElapsedS = DATEDIFF(second, @start_date, @end_date)
Run Code Online (Sandbox Code Playgroud)
现在创建以下标量函数:
CREATE FUNCTION [dbo].[udfTimeSpanFromSeconds]
(
@Seconds int
)
RETURNS varchar(15)
AS
BEGIN
DECLARE
--Variable to hold our result
@DHMS varchar(15)
--Integers for doing the math
, @Days int --Integer days
, @Hours int --Integer hours
, @Minutes int --Integer minutes
--Strings for providing the display
, @sDays varchar(5) --String days
, @sHours varchar(2) --String hours
, @sMinutes varchar(2) --String minutes
, @sSeconds varchar(2) --String seconds
--Get the values using modulos where appropriate
SET @Hours = @Seconds/3600
SET @Minutes = (@Seconds % 3600) /60
SET @Seconds = (@Seconds % 3600) % 60
--If we have 24 or more hours, split the @Hours value into days and hours
IF @Hours > 23
BEGIN
SET @Days = @Hours/24
SET @Hours = (@Hours % 24)
END
ELSE
BEGIN
SET @Days = 0
END
--Now render the whole thing as string values for display
SET @sDays = convert(varchar, @Days)
SET @sHours = RIGHT('0' + convert(varchar, @Hours), 2)
SET @sMinutes = RIGHT('0' + convert(varchar, @Minutes), 2)
SET @sSeconds = RIGHT('0' + convert(varchar, @Seconds), 2)
--Concatenate, concatenate, concatenate
SET @DHMS = @sDays + ':' + @sHours + ':' + @sMinutes + ':' + @sSeconds
RETURN @DHMS
END
Run Code Online (Sandbox Code Playgroud)
现在将您的时间跨度输入到新创建的函数中:
SELECT TimeSpan = dbo.udfTimeSpanFromSeconds(@ElapsedS)
Run Code Online (Sandbox Code Playgroud)
应该产生'1:09:19:01'
小智 15
CONVERT(varchar,(@end_date-@start_date),108)
Run Code Online (Sandbox Code Playgroud)
这将给你作为HH:MM:SS
干杯