Java 8 date/time classes in Android below api 26

The old Java classes for handling dates and times are terrible. Date, Calendar, SimpleDateFormat, etc., are badly designed, buggy, and very difficult to use for anything other than the most basic date/time handling.

If your minimum Android sdk is 26 (Oreo) then you can use the newer Java 8 date/time classes instead of these old problematic classes, which can save a whole load of time and potential bugs. But not many projects have the luxury of targeting 26 and above; on my latest app I thought I was being aggressive by setting the minimum sdk to 24 (Nougat), and on most client projects I work on the minimum is less than this.

Until recently I have been using the most excellent ThreeTen Android Backport, which does a very good job of providing most of the functionality that the Java 8 classes provide. But since Android Gradle plugin 4.0 there comes a new, even better option:


Core library desugaring

Core library what? That’s what I thought anyway. Basically it means you can use some of the Java 8 features on any version of Android, as described here.

And crucially this includes most of the Java 8 java.time classes, which make it so much easier to handle date and time functions like timezones, date and time span calculations, and date time formatting in a thread-safe way.


Implementation

To use these classes you have to use the Android Gradle plugin version 4.0+. This is set in you project level build.gradle file:

buildscript {
    .
    .
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.2'
        .
        .
    }
}

Then in your module level build.gradle file you need to set the Java version to 1.8, and set coreLibraryDesugaringEnabled to true. I also have the Kotlin options set to Java 8, not sure if this is needed for this but it seems like a sensible setting anyway:

android {
    .
    .
    compileOptions {
        coreLibraryDesugaringEnabled true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

Finally in the same module level build.gradle file add the dependency for the desugaring library:

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

And that’s it. Proper date and time functionality in any Android app. Take a look at this for an introduction to the APIs.


Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.