【问题标题】:An alternative to DateTimeFormatter in Android API-21Android API-21 中 DateTimeFormatter 的替代方案
【发布时间】:2021-05-15 20:54:44
【问题描述】:

我的应用在运行时崩溃。它在我第一次构建和编译它时工作,但现在它没有。我认为这是由于“DateTimeFormatter”无法在我当前的 api 级别 21 中使用。有解决方法吗?

这是错误:

java.lang.NoClassDefFoundError: Failed resolution of: Ljava/time/format/DateTimeFormatter;

以下是受影响的代码:

@RequiresApi(api = Build.VERSION_CODES.O)
public boolean checkTimeAgainstCurrentTime(String time) throws ParseException {
    boolean isTime = false;
    DateTimeFormatter parser = DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
    LocalTime theTime = LocalTime.parse(time, parser);
    Date time1 = new Date(System.currentTimeMillis());
    Date time2 = new SimpleDateFormat("HH:mm:ss").parse(theTime + ":00");
    time1.setHours(time2.getHours());
    time1.setMinutes(time2.getMinutes());
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date today = Calendar.getInstance().getTime();
    today.setHours(today.getHours()+8);
    if (today.after(time1)) {
        isTime = true;
    }
    // If true, means expired.
    return isTime;
}

【问题讨论】:

    标签: java android android-studio android-api-levels


    【解决方案1】:

    您可以启用 API Desugaring 以实现向后兼容性,这里 https://developer.android.com/studio/write/java8-support#library-desugaring 是它的说明,但实际上您必须添加一行代码,如下面的应用程序级别 build.gradle 所示。

    android {
      compileOptions {
        coreLibraryDesugaringEnabled true
      }
    }
    

    你需要一个依赖

    dependencies {
      coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-06
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 2016-02-21
      相关资源
      最近更新 更多