Reputation: 21
I have a system that sum up all the hours(converted to milliseconds), if that hour is more than 24 hours(eg, 26 hours), it will back to 02:00:00
instead of 26:00:00
.
totH = parser.parse(totalH);
totHTotal += totH.getTime(); // assume totHTotal gets 93600000.
totalHours = parser.format(new Date(totHTotal));
System.out.println(totalHours); // this will output 02:00:00 but I want this to output 26:00:00.
Can somebody help me, thank you.
Upvotes: 0
Views: 1700
Reputation: 401
You could use a Duration or do the arithmetic.
1 hour: 3 600 000ms
1 minute: 60 000ms
1 second: 1 000ms
You can run it here: https://repl.it/GLLH/9
import java.time.Duration;
class Main {
public static void main(String[] args) {
System.out.println("Using math");
long millsMath = 93631000;
long hoursMath = millsMath / 3600000;
long minutesMath = (millsMath % 3600000) / 60000;
long secondsMath = (millsMath % 60000) / 1000;
String outMath = String.format("%02d:%02d:%02d",hoursMath, minutesMath, secondsMath);
System.out.println(outMath);
System.out.println("\nUsing Duration");
Duration dur = Duration.ofMillis(93631000);
long hoursDur = dur.toHours();
long minutesDur = dur.minusHours(hoursDur).toMinutes();
long secondsDur = dur.minusHours(hoursDur).minusMinutes(minutesDur).getSeconds();
String outDur = String.format("%02d:%02d:%02d", hoursDur, minutesDur, secondsDur);
System.out.println(outDur);
}
}
output:
Using math 26:00:31 Using Duration 26:00:31
Upvotes: 1