Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Milliseconds to Days, hours, minutes and seconds

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!

like image 956
Christian Casutt Avatar asked Oct 06 '12 07:10

Christian Casutt


People also ask

How do you convert milliseconds into hours minutes and seconds?

To convert milliseconds to hours, minutes, seconds: Divide the milliseconds by 1000 to get the seconds. Divide the seconds by 60 to get the minutes. Divide the minutes by 60 to get the hours. Add a leading zero if the values are less than 10 to format them consistently.

How do you convert milliseconds to days hours minutes seconds in Java?

Show activity on this post. long seconds = timeInMilliSeconds / 1000; long minutes = seconds / 60; long hours = minutes / 60; long days = hours / 24; String time = days + ":" + hours % 24 + ":" + minutes % 60 + ":" + seconds % 60; This will work if you have more than 28 days, but not if you have a negative time.


1 Answers

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
like image 127
RichardTheKiwi Avatar answered Oct 24 '22 16:10

RichardTheKiwi