How To Format Duration String Like Pt3m33s To Hh:mm:ss
i've been searching StackOverflow's posts about this specific date type, also i've checked on google's search engine to verify the name of this date type. So far what i've learned
Solution 1:
You can use java.time.Duration
which 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 PT3M33S
specifies a duration of 3 minutes 33 seconds that you can parse to a Duration
object and 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;
publicclassMain {
publicstaticvoidmain(String[] args) {
String strIso8601Duration = "PT3M33S";
Duration duration = Duration.parse(strIso8601Duration);
// Default formatSystem.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:
PT3M33S
00:03:3300:03:33
Learn about the modern date-time API from Trail: Date Time.
- For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
- If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Post a Comment for "How To Format Duration String Like Pt3m33s To Hh:mm:ss"