Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

algorithm - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...