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.
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?
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.
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);
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With