select cast(datediff(minute,convert(time,'09:35 AM'),
convert(time,'07:06 PM'))/60 as varchar)
+':'+cast(datediff(minute,convert(time,'09:35 AM'),
convert(time,'07:06 PM'))%60 as varchar)
输出:9:31
我是否还有其他功能可以缩短上述脚本。另外,我应该怎么做才能将输出变为09:31
而不是9:31
?
答案 0 :(得分:5)
您可以使用样式114的CONVERT()
来获取HH:mm
SELECT
CONVERT(nvarchar(5),
-- Get difference of time
CONVERT(datetime,'07:06 PM') - CONVERT(datetime,'09:35 AM')
, 114)
修改强>
作为评论以避免日期时算术
SELECT CONVERT(varchar(5),
DATEADD(minute,
DATEDIFF(minute, convert(time,'09:35 AM'), convert(time,'07:06 PM'))
, 0)
, 114)
答案 1 :(得分:0)
您可以在Sql Server中使用Format功能。
更新 - (示例):这可能是您想要的:
select FORMAT(CONVERT(datetime,'9:31'),'HH:mm') AS 'time'
答案 2 :(得分:0)
DECLARE @time1 AS VARCHAR(8) = '09:35 AM'
DECLARE @time2 AS VARCHAR(8) = '07:06 PM'
SELECT
time1 = CAST(@time1 AS TIME),
time2 = CAST(@time2 AS TIME),
diff = DATEDIFF(MINUTE, @time1, @time2),
hh = RIGHT('00' + CAST(DATEDIFF(MINUTE, CAST(@time1 AS TIME), CAST(@time2 AS TIME))/60 AS VARCHAR(2)), 2),
mm = RIGHT('00' + CAST(DATEDIFF(MINUTE, CAST(@time1 AS TIME), CAST(@time2 AS TIME))%60 AS VARCHAR(2)), 2),
final = RIGHT('00' + CAST(DATEDIFF(MINUTE, CAST(@time1 AS TIME), CAST(@time2 AS TIME))/60 AS VARCHAR(2)), 2) + ':' +
RIGHT('00' + CAST(DATEDIFF(MINUTE, CAST(@time1 AS TIME), CAST(@time2 AS TIME))%60 AS VARCHAR(2)), 2)
在声明和/或转换为VARCHAR
类型时,您应指定长度,否则SQL-Server将为您分配默认值。有时它是1
,有时它是30
。有关详细信息,请参阅此article。
另外,要将差异格式化为hh:mm
,您需要使用适当的零数填充字符串。这是使用:
RIGHT('00' + str, 2)
答案 3 :(得分:0)
只需尝试此广告检查是否符合您的要求:
SELECT FORMAT(GETDATE(),'hh:mm')
OR
SELECT (CONVERT(VARCHAR(5), GETDATE(), 114))