Converting Milliseconds to Days, hours, minutes and seconds

馋奶兔 提交于 2019-12-10 13:09:10

问题


i have a bigint field in Microsoft SQL Server 2008R2 filled with ticks (A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.)

http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx

and i need to convert the sum of all records to Days:Hours:Minutes:Seconds:Milliseconds.

it works for a single record:

SELECT CONVERT(TIME, DATEADD(ms, duration/10000, 0)) FROM tblMediaFileProperties WHERE FileId = '6C0A849D-95B4-4755-A923-B9DD8F1AF23E'

but if a sum it up to all records using:

SELECT CONVERT(TIME, DATEADD(ms, SUM(duration/10000), 0)) FROM tblMediaFileProperties 

i get a:

Arithmetic overflow error converting expression to data type int.

i know the overflow comes from the CONVERT to Data Type TIME Function...

help's appreciated, thanks!


回答1:


It's too big for DATEADD which only accepts an int.
Break it into two parts: seconds, then milliseconds.

SELECT CONVERT(TIME,
          DATEADD(ms, SUM(duration/10000 % 1000),
          DATEADD(ss, SUM(duration/10000000), 0)))
FROM tblMediaFileProperties 

And if your total duration goes above 1 day, you can use this to get the days and hr:min:sec:ms separately. It's a matter of cast and string concat if you actually want the result in textual form.

declare @duration bigint
set @duration = 1230000000
SELECT @duration/10000/1000/60/60/24 DAYS,
       CONVERT(TIME,
          DATEADD(ms, SUM(@duration/10000 % 1000),
          DATEADD(ss, SUM(@duration/10000000), 0))) HR_MIN_SEC


来源:https://stackoverflow.com/questions/12757811/converting-milliseconds-to-days-hours-minutes-and-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!