Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From milliseconds to hour, minutes, seconds and milliseconds

I need to go from milliseconds to a tuple of (hour, minutes, seconds, milliseconds) representing the same amount of time. E.g.:

10799999ms = 2h 59m 59s 999ms

The following pseudo-code is the only thing I could come up with:

# The division operator below returns the result as a rounded down integer function to_tuple(x):     h = x / (60*60*1000)     x = x - h*(60*60*1000)     m = x / (60*1000)     x = x - m*(60*1000)     s = x / 1000     x = x - s*1000     return (h,m,s,x) 

I'm sure it must be possible to do it smarter/more elegant/faster/more compact.

like image 975
Mads Skjern Avatar asked Jun 03 '12 21:06

Mads Skjern


People also ask

How do you convert milliseconds to HH MM SS format in Excel?

So all you need to do is divide the data you have in milliseconds by 86,400,000. Format the result as [h]:mm:ss and you are done. Note that if the value is more than 86,400,000, then you have deal with that, by adjusting the hours. Was this reply helpful?

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.


2 Answers

Here is how I would do it in Java:

int seconds = (int) (milliseconds / 1000) % 60 ; int minutes = (int) ((milliseconds / (1000*60)) % 60); int hours   = (int) ((milliseconds / (1000*60*60)) % 24); 
like image 199
Alex W Avatar answered Sep 18 '22 14:09

Alex W


Good question. Yes, one can do this more efficiently. Your CPU can extract both the quotient and the remainder of the ratio of two integers in a single operation. In <stdlib.h>, the function that exposes this CPU operation is called div(). In your psuedocode, you'd use it something like this:

function to_tuple(x):     qr = div(x, 1000)     ms = qr.rem     qr = div(qr.quot, 60)     s  = qr.rem     qr = div(qr.quot, 60)     m  = qr.rem     h  = qr.quot 

A less efficient answer would use the / and % operators separately. However, if you need both quotient and remainder, anyway, then you might as well call the more efficient div().

like image 28
thb Avatar answered Sep 19 '22 14:09

thb