I recommend not using java.util.Date
. It's a little awkward. If you are permitted to use a third-party library, I recommend the JSR-310 backport.
Since you're using Android, you'll need to include this library just as you would in a standard Java 7 project, even if you use the jack compiler, as java.time
is not yet available in the Android SDK.
Setup
In your app's build.gradle
dependencies list, you can add the Android adaption of the threeten library:
compile "com.jakewharton.threetenabp:threetenabp:1.0.4"
...and if you need to be able run standard Java unit tests that use threeten, you can exclude the Android portion and include the threeten library itself by adding this also (may not be necessary if you use Roboelectric, but I'm not 100% sure):
testCompile ('org.threeten:threetenbp:1.3.2') {
exclude module: 'com.jakewharton.threetenabp:threetenabp:1.0.3'
}
Then you'd need this to initialize the Android library in your application:
// e.g. in your Application subclass
@Override
public void onCreate() {
AndroidThreeTen.init(this);
}
Usage
Now you can do this:
LocalDate dateBefore = LocalDate.of(2017, 3, 1);
LocalDate dateAfter = LocalDate.of(2017, 3, 31);
long daysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);
assertEquals(30, daysBetween);