3

I am trying to find days difference between two dates. I am using JDK 1.7 (cannot change it). Somehow JDK ignores March 9th in difference calculations, while JODA API calculates it correctly. Here is the code i executed using TimeUnit and JODA API.

    String dateStart = "11/16/2019 00:00:00";
    String dateStop = "05/15/2020 00:00:00";
    SimpleDateFormat format2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    firstDate = format2.parse(dateStart);
    secondDate = format2.parse(dateStop);

    long diffInMillies =  secondDate.getTime() - firstDate.getTime();
    long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
    System.out.println(">>>>>>>>>>>>");
    System.out.println("difference in days is  " + diff);

   // Days.bet(firstDate, secondDate);
    DateTime dateTime1 = new DateTime(firstDate.getTime());
    DateTime dateTime2 = new DateTime(secondDate.getTime());
    System.out.println("Difference by JODA API " +  Days.daysBetween(dateTime1,dateTime2 ).getDays());

Here the output i got, Seems a bug in JDK. Could anyone please let me know if i am mistaken.

Difference in days is  180
Difference by JODA API 181
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Sunil
  • 93
  • 1
  • 7
  • 2
    Why are you comparing the old legacy date api of Java with a proper date api like JODA? It does not respect most of the weird phenomens of real world time. This is not a bug but just you expecting too much from the old date api. Use `java.time` instead (heavily inspired/ported from JODA). Also, which timezones do you want to use? The date difference is possibly different per region. – Zabuzard May 15 '20 at 17:32
  • "Seems a bug in JDK" breaking news: j.u.Date is trash – Michael May 15 '20 at 17:34
  • 1
    Also, there is a backport to Java 1.7. So you can use `java.time` as well. See [ThreeTen Backport](https://www.threeten.org/threetenbp/). – Zabuzard May 15 '20 at 17:40
  • 1
    Sunil - Did you check https://stackoverflow.com/a/3491723/10819573? – Arvind Kumar Avinash May 15 '20 at 17:51
  • Check out: https://stackoverflow.com/a/31800947/4561314 – stackoverflowuser2010 May 15 '20 at 18:45

0 Answers0