Difference in Days between two Java dates?

前端 未结 5 1503
南方客
南方客 2021-01-06 06:21

I want to get the difference between two Java Date objects. I\'ve used Joda-Time library. But the problem is that I\'m getting the Days greater difference than that of actua

5条回答
  •  再見小時候
    2021-01-06 06:59

    The other answers correctly solved your specific problem.

    LocalDate

    But there is a larger solution. If you are starting with only dates, no time-of-day and no time zones, then you should be using the LocalDate class rather than DateTime.

    Time Zone

    Your code ignores the crucial issue of time zones. Time zones matter even for LocalDate, when trying to determine "today". Do you want today's date in Montréal or in Paris. A new day dawns in Paris earlier. When you omit time zone, you get the JVM’s current default time zone.

    Joda-Time Can Parse

    Furthermore, let Joda-Time do the parsing. No need to be using java.util.Date & .Calendar at all. Joda-time's formatting characters are almost the same as java.util.Date but not entirely so be sire to consult the doc. In this case it it identical.

    DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
    LocalDate past = formatter.parseLocalDate( "06/22/2010" );
    DateTimeZone = DateTimeZone.forID( "America/Montreal" ): // match time zone intended for that input string.
    int days = Days.daysBetween( past, LocalDate.now( timeZone ) );
    

提交回复
热议问题