如何降级旧 Android 中的 java.time 代码?

How to downgrade java.time code in older Android?

我有这个整洁的代码,它生成两个日期之间的天数列表,然后是当天的日期,以及它在列表中的位置(最重要的是,所有日期都在同一个格式,便于比较它们)。

//Create list of days
String s = "2018-08-28";
String e = "2018-09-05";
LocalDate start = LocalDate.parse(s);
LocalDate end = LocalDate.parse(e);
List<LocalDate> totalDates = new ArrayList<>();
while (!start.isAfter(end)) {
    totalDates.add(start);
    start = start.plusDays(1);
}

//Date and place of current day
LocalDate a = LocalDate.now();
int current_day = totalDates.indexOf(a) + 1;

问题是当我在 Java IDE 中玩这段代码时,我不知道它的某些部分 (.parse() ; .now() ; .isAfter() ; .plusDays()) 是为 26+ 保留的API 级手机。或者,我的应用程序应该工作的最大值 API 是 API 23.

我想知道如何以最有效的方式 "downgrade" 它,但我不知道该做什么或从哪里开始。

后端口

不需要"downgrade"。大多数 java.time 功能已向后移植。

ThreeTen-Backport 库添加到您的项目中,特别适用于 Android ThreeTenABP 项目。请参阅下方链接。

遗留的日期时间 类 是一个可怕的丑陋的烂摊子——永远不要使用它们。

顺便说一下,您提到的那些文本格式是标准的,在 ISO 8601 中定义。 java.time 类 在 parsing/generating 字符串时默认使用这些格式。


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time 类.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类.

在哪里获取java.time类?

不再需要 ThreeTeenABP 在旧版本的 Android 平台上启用对这些语言 API 的支持。 您可以使用核心库脱糖。

只需将 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.10'
}