Tuesday, April 18, 2017

How to use java.time in Android

Java 8's java.time package (a.k.a. JSR-310) is very useful for dealing with timestamps and timezones, etc.  But at the time of this writing, the Android SDK only includes Java 7, so the java.time package is not available to Android projects.  There are alternative libraries out there for working with time, such as Joda-Time or Date4j, but they have various shortcomings, and java.time is regarded to be the standard going forward. Fortunately, JSR-310 has been backported to Java 7 and 6 by Stephen Colebourne & Michael Nascimento Santos (http://www.threeten.org/threetenbp/). 

However, you shouldn't simply grab the main threetenbp jar and add it to your Android project, because it includes the olson time zone database in its jar file, and in Android, loading resources from jars has a huge memory overhead.  Instead, include the no-tzdb.jar, which does not include the database.  And then, use Jake Wharton's ThreeTenABP aar, which provides the database to ThreeTenBP as an Android resource, much more efficiently.   

If you're using mavenCentral (the default) include the following in your module's build.gradle file, in the dependencies section:
    compile 'com.jakewharton.threetenabp:threetenabp:1.0.5'
If you prefer to work offline, you can do the following:

obtain or build a copy of the com.jakewharton.threetenabp aar and the org.threeten.threetenbp no-tzdb jar
put the no-tzdb jar in a folder named "libs" in the root of your module project
put threetenabp aar file in a folder names android-libs in the root of your module project.
include the following lines in your build.gradle file:

    allprojects {
        repositories {

            flatDir {
                dirs 'android-libs'
            }

        }
    }


    ...
    dependencies {

        compile fileTree(include: ['*.jar'], dir: 'libs')
        compile(name: 'threetenabp-x.x.x', ext: 'aar')

    }


Then in your java code, where you would use
import java.time
just use
import org.threeten.bp
and you can use the Java 8 time APIs in your Android project!