You are almost there
java.time.Duration
is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenience methods were introduced.
If you have gone through the above links, you might have already noticed that PT12M35S
specifies a duration of 12 minutes 35 seconds. Since you have already got Duration
object, out of this object, you can create a string formatted as per your requirement by getting days, hours, minutes, seconds from it.
Demo:
import java.time.Duration;
public class Main {
public static void main(String[] args) {
Long downTime = 755L;
Duration duration = Duration.ofSeconds(downTime);// PT12M35S
// Default format
System.out.println(duration);
// Custom format
// ####################################Java-8####################################
String formattedElapsedTime = String.format("%02d:%02d:%02d", duration.toHours() % 24,
duration.toMinutes() % 60, duration.toSeconds() % 60);
System.out.println(formattedElapsedTime);
// ##############################################################################
// ####################################Java-9####################################
formattedElapsedTime = String.format("%02d:%02d:%02d", duration.toHoursPart(), duration.toMinutesPart(),
duration.toSecondsPart());
System.out.println(formattedElapsedTime);
// ##############################################################################
}
}
Output:
PT12M35S
00:12:35
00:12:35
Learn about the modern date-time API from Trail: Date Time.
Duration and date are different concepts
Your requirement is to calculate the duration instead of a date-time. SimpleDateFormat
or java.time.format.DateTimeFormatter
(part of the modern date-time API) should be used to represent a date/time/date-time i.e. something which represents a point in time instead of a period/duration of time. A thumb rule to remember this is:
- Use
SimpleDateFormat
or java.time.format.DateTimeFormatter
for something which you refer with since
in English grammar Tense.
- Use Period and Duration for something which you refer with
for
in English grammar Tense.
Check The Difference between Since and For – English grammar