我目前正在使用一个 SQL 脚本来计算两个日期之间的差异,这将为我提供 DD:HH:MI:SEC 格式的结果。示例:日期 1:2012 年 7 月 30 日下午 4:00 日期 2:2012 年 5 月 4 日上午 10:31
结果应该是 87:05:29:00
你能帮忙写这个脚本吗?问候, 阿琼
如果您使用的是 sql-server,那么您可以这样做:
declare @x int,
@dt1 smalldatetime = '1996-03-25 03:24:16',
@dt2 smalldatetime = getdate()
set @x = datediff (s, @dt1, @dt2)
SELECT convert(varchar, @x / (60 * 60 * 24)) + ':'
+ convert(varchar, dateadd(s, @x, convert(datetime2, '0001-01-01')), 108)
参考这里
Well, you if want to perform some calculation, you could do this as well:
DECLARE @SecsInADay INT = 60 * 60 * 24
DECLARE @DATE1 DATETIME = CONVERT(DATETIME,'30/07/2012 16:00:00')
DECLARE @DATE2 DATETIME = CONVERT(DATETIME,'04/05/2012 10:31:00')
DECLARE @Days INT = DATEDIFF(DAY, @DATE2, @DATE1)
DECLARE @DiffInSeconds INT = DATEDIFF(SECOND, @DATE2, @DATE1)
DECLARE @TotalDaysInSeconds INT = @Days * @SecsInADay
DECLARE @RemainingHours INT = @DiffInSeconds - @TotalDaysInSeconds
DECLARE @Hours INT = @RemainingHours / 3600
DECLARE @Seconds INT = @RemainingHours % 3600
DECLARE @Minutes INT = @Seconds / 60
DECLARE @RemainingSeconds INT = @Seconds % 60
SELECT
CASE WHEN @Days < 10 THEN '0' + CAST(@Days AS VARCHAR) ELSE CAST(@Days AS VARCHAR) END + ':' +
CASE WHEN @Hours < 10 THEN '0' + CAST(@Hours AS VARCHAR) ELSE CAST(@Hours AS VARCHAR) END + ':' +
CASE WHEN @Minutes < 10 THEN '0' + CAST(@Minutes AS VARCHAR) ELSE CAST(@Minutes AS VARCHAR) END + ':' +
CASE WHEN @RemainingSeconds < 10 THEN '0' + CAST(@RemainingSeconds AS VARCHAR) ELSE CAST(@RemainingSeconds AS VARCHAR) END
嗨,我有一个类似的问题,花了一些时间思考,这是我的解决方案,我有用户订阅的表格,开始时间和结束时间很糟糕,我的问题有点复杂,基本上归结为:
SELECT subscription_id, time_open, time_closed, TIMESTAMPDIFF(DAY,time_open,time_closed) AS Day,
HOUR(sec_to_time(TIMESTAMPDIFF(SECOND,ADDDATE(`time_open`, INTERVAL TIMESTAMPDIFF(DAY,time_open,time_closed) DAY),`time_closed`))) AS Hour,
MINUTE(sec_to_time(TIMESTAMPDIFF(SECOND,ADDDATE(`time_open`, INTERVAL TIMESTAMPDIFF(DAY,time_open,time_closed) DAY),`time_closed`))) AS Minute,
SECOND(sec_to_time(TIMESTAMPDIFF(SECOND,ADDDATE(`time_open`, INTERVAL TIMESTAMPDIFF(DAY,time_open,time_closed) DAY),`time_closed`))) AS Second
FROM `user_subscription`
所以基本上这个查询所做的是它通过在第一行中推断日期来计算天数。然后它将全天数添加到开始时间并减少关闭时间我的总和,所以剩下的是当天的时间。之后,您只需从中选择小时、分钟和秒。如果您想将它们全部连接在一起,则可以将字符串连接起来,但与字符串不同,这样您可以进一步使用它。