【问题标题】:ISO 8601 Time Duration Parsing in Java 7Java 7 中的 ISO 8601 持续时间解析
【发布时间】:2020-09-29 14:35:20
【问题描述】:

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

【问题讨论】:

    标签: android datetime java-7 iso8601


    【解决方案1】:

    好消息!现在您可以使用 Android Gradle 插件 4.0.0+ 对 java.time API 进行脱糖

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

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

    这里有脱糖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'
    }
    

    【讨论】:

      【解决方案2】:

      如果您的 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 引入的。

      【讨论】:

      • 现在好像是Period 而不是Duration
      • @Boy - No. Period 和 Duration 用于类似目的,但用于不同类型。 Duration 需要有一个时间组件。要了解更多信息,请查看3rd link in my answer
      猜你喜欢
      • 2014-07-16
      • 2014-08-16
      • 2021-05-21
      • 2010-11-11
      • 2013-04-05
      • 2021-02-16
      • 2021-12-12
      • 1970-01-01
      • 2021-10-07
      相关资源
      最近更新 更多