我正在解析YouTube API v3,并试图提取似乎采用ISO8601格式的持续时间。现在,Java 8中有内置的方法,但这要求我必须将API级别提高到26 (Android ),这是我做不到的。有什么方法来解析它吗?我使用的示例字符串是:PT3H12M
发布于 2020-09-29 15:11:39
好消息!现在,您可以使用Android插件4.0.0+来处理4.0.0+ API。
https://developer.android.com/studio/write/java8-support#library-desugaring
因此,这将允许您使用与Java相关的Java8的内置方法:)
这里有desugared的详细规范:
https://developer.android.com/studio/write/java8-support-table
您只需将安卓插件的版本添加到4.0.0+,并将这些行添加到应用程序模块级别的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'
}发布于 2020-09-29 21:22:46
如果您的Android级别仍然不符合Java-8,请检查通过desugaring提供的Java 8+ API和如何在安卓项目中使用ThreeTenABP。
下面的部分将讨论如何使用现代日期时间API来完成这一任务。
与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")));
}
}输出:
3:12 am与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")));
}
}输出:
3:12 am请注意,Duration#toHoursPart和Duration#toMinutesPart是在Java-9中引入的。
https://stackoverflow.com/questions/64121853
复制相似问题