Java 7中的ISO 8601时间持续时间解析

问题描述

我正在解析YouTube API v3,并尝试提取似乎采用ISO 8601格式的持续时间。现在,Java 8中有内置的方法,但这要求我必须将API级别提高到26(Android O),而我不能这样做。有什么办法可以本地解析吗?我使用的示例字符串是:PT3H12M

解决方法

好消息!现在,您可以使用Android Gradle插件4.0.0 +

来对java.time API进行解糖

https://developer.android.com/studio/write/java8-support#library-desugaring

因此,这将允许您使用Java 8中与java.time api相关的内置方法:)

在这里,您有详细的desugared api规范:

https://developer.android.com/studio/write/java8-support-table

您只需要做的就是将Android插件的版本提高到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'
}
,

如果您的Android API级别仍不符合Java-8,请选中Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

以下部分讨论如何使用modern date-time 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#toHoursPartDuration#toMinutesPart是Java-9引入的。