1

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

Community
  • 1
  • 1

2 Answers2

2

As mentioned in previous comments, Joda-Time counts whole days and rounds down. Therefore you'll need to skip the time when comparing. Something like this will work, using Java.time comparing the dates:

Date date1 = new Date("Mon Sep 10 08:32:58 GMT 2018");
Date date2 = new Date("Tue Sep 11 03:56:10 GMT 2018");
LocalDate start = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate end = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
long between = ChronoUnit.DAYS.between(start, end);

System.out.println("Date difference: " + between);
joese
  • 86
  • 6
  • Are you using java.time rather than Joda-Time? A nice idea, but better to make it clear, please. – Ole V.V. Sep 11 '18 at 06:32
  • Yes, I was using java.time instead of yodatime when calculating the days between. Thanks for your constructive comment. The answer is updated with a clarification. – joese Sep 11 '18 at 07:12
2

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.)

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161