0

I'm trying to count the number of days between two dates in March, but I'm getting the wrong result.

When dateBefore is 01/03/2017 and dateAfter is 31/03/2017, diff is 29 days but should be 30 (31-1)?

public static int daysBetweenDates2(Date dateBefore, Date dateAfter) { 
    long diff = (dateAfter.getTime() - dateBefore.getTime())/(24*60*60*1000);
    return (int)diff;
}
drhr
  • 2,261
  • 2
  • 17
  • 35

1 Answers1

2

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); 
drhr
  • 2,261
  • 2
  • 17
  • 35
  • this will count only "full days" if you compare 2016.01.01 23:30 to 2016.01.02 18:30 it will return 0 days difference – Dmitrijs Dec 18 '16 at 15:10
  • Correct, when using `LocalDateTime` instead. That's why `LocalDate` is used here. `ChronoUnit.DAYS.between` accepts `Temporal` parameters, which _can_ be `LocalDateTime`, but that would cause your date-times to not register as a full day's difference. – drhr Dec 18 '16 at 22:27