I want to convert an elapsed amount of accumulated seconds into hours:minutes:seconds. For example
93599 seconds to:
25:59:59
How can I do that? (Note: 24h should not wrap to 0h)
I want to convert an elapsed amount of accumulated seconds into hours:minutes:seconds. For example
93599 seconds to:
25:59:59
How can I do that? (Note: 24h should not wrap to 0h)
The modulus operator %
is useful here. Something like this would work well
public static void convertTime(int seconds) {
int secs = seconds % 60;
int mins = (seconds / 60) % 60;
int hours = (seconds / 60) / 60;
System.out.printf("%d:%d:%d", hours, mins, secs);
}
Java 8 provides the java.time.Duration
class for expressing amounts of time. You can use Duration#ofSeconds(long)
to build an instance from an amount of seconds.
Duration ellapsed = Duration.ofSeconds(93599);
However, the default toString
format looks like
PT25H59M59S
which isn't what you want. You can do the math yourself (with the various toMinutes
, toHours
, etc.) to convert it to the format you want. An example is given here.
hours = 93599 / 3600. Use integer arithmetic to force a truncation.
Then subtract hours * 3600 from 93599. Call that foo. Or compute 93599 % 3600.
minutes = foo / 60. Use integer arithmetic.
Subtract minutes * 60 from foo. Call that bar. Or compute foo % 60.
bar is the remaining seconds.
Copy and use this Class:
public class AccumulatedTimeFormat extends Format {
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
Long totalSeconds;
if(obj instanceof Byte) {
totalSeconds=((Byte)obj).longValue();
} else if(obj instanceof Short) {
totalSeconds=((Short)obj).longValue();
} else if(obj instanceof Integer) {
totalSeconds=((Integer)obj).longValue();
} else if(obj instanceof Long) {
totalSeconds=((Long)obj);
} else {
throw new IllegalArgumentException("Cannot format given Object as an accumulated-time String!");
}
long ss = Math.abs(totalSeconds) % 60;
long mm = (Math.abs(totalSeconds) / 60) % 60;
long h = (Math.abs(totalSeconds) / 60) / 60;
if(totalSeconds<0) {
toAppendTo.append('-');
}
toAppendTo.append(String.format("%d:%02d:%02d", h, mm, ss));
return toAppendTo;
}
@Override
public Object parseObject(String source, ParsePosition pos) {
//TODO Implement if needed!
return null;
}
}
Like this:
System.out.println((new AccumulatedTimeFormat()).format(93599));
Which prints:
25:59:59