Search code examples
javadatejava-7jodatimedate-difference

Date difference in days for Java7


I have date formats as: EEE, dd MMM yyyy HH:mm:ss Z

For ex.,

Date 1 : Mon Sep 10 08:32:58 GMT 2018

Date 2 : Tue Sep 11 03:56:10 GMT 2018

I need date difference as 1 in above case, but I am getting value as 0 if I use joda date time or manually converting date to milliseconds.

For reference : http://www.mkyong.com/java/how-to-calculate-date-time-difference-in-java/

Any leads will be helpful. Example :

Date date1 = new Date("Mon Sep 10 08:32:58 GMT 2018");
Date date2 = new Date("Tue Sep 11 03:56:10 GMT 2018");
DateTime start = new DateTime(date1 );
DateTime end = new DateTime(date2);
int days = Days.daysBetween(start, end).getDays();
System.out.println("Date difference: " + days);

Output: Date difference: 0


Solution

  • Joda-Time counts only whole days, in other words, truncates the difference to a whole number. So with a little over 19 hours between your values it counts as 0 days. If you want to ignore the time part of the dates, convert to LocalDate first:

        int days = Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays();
    

    (Thanks for providing the concrete code yourself in a comment. Since you said it worked, I thought it deserved to be an answer.)