I am parsing the YouTube API v3 and trying to extract the duration which seems to be in ISO 8601 format. Now, there are inbuilt methods in Java 8, but that requires that I would have to bump the API level to 26 (Android O), which I cannot do. Any way to parse it natively? Example string I am using is: PT3H12M

- 168
- 1
- 7
2 Answers
Good news! Now you can desugar the java.time API with the Android Gradle plugin 4.0.0+
https://developer.android.com/studio/write/java8-support#library-desugaring
So this will allow you using inbuilt methods from Java 8 related to java.time api :)
Here you have detailed specification of desugared api:
https://developer.android.com/studio/write/java8-support-table
And what you only need to do is to bump the version of Android plugin to 4.0.0+ and add those lines to your app-module level build.gradle:
android {
defaultConfig {
// Required when setting minSdkVersion to 20 or lower
multiDexEnabled true
}
compileOptions {
// Flag to enable support for the new language APIs
coreLibraryDesugaringEnabled true
// Sets Java compatibility to Java 8
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
}

- 1,549
- 10
- 12
If 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.
The following section talks about how you can do it using the modern date-time API.
With Java-8:
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
Duration duration = Duration.parse("PT3H12M");
LocalTime time = LocalTime.of((int) duration.toHours(), (int) (duration.toMinutes() % 60));
System.out.println(time.format(DateTimeFormatter.ofPattern("h:m a")));
}
}
Output:
3:12 am
With Java-9:
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
Duration duration = Duration.parse("PT3H12M");
LocalTime time = LocalTime.of(duration.toHoursPart(), duration.toMinutesPart());
System.out.println(time.format(DateTimeFormatter.ofPattern("h:m a")));
}
}
Output:
3:12 am
Note that Duration#toHoursPart
and Duration#toMinutesPart
were introduced with Java-9.

- 71,965
- 6
- 74
- 110
-
seems like this is `Period` now instead of `Duration`? – Boy Jul 05 '21 at 13:58
-
@Boy - No. Period and Duration are for similar purposes but to be used with different types. `Duration` requires to have a time component. To learn more about it, please check the [3rd link in my answer](https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html). – Arvind Kumar Avinash Jul 05 '21 at 14:26