Number of days between two dates in Joda-Time

后端 未结 8 1039
北恋
北恋 2020-11-22 09:07

How do I find the difference in Days between two Joda-Time DateTime instances? With ‘difference in days’ I mean if start is on Monday and end is on Tuesday I expect a return

相关标签:
8条回答
  • 2020-11-22 09:59

    java.time.Period

    Use the java.time.Period class to count days.

    Since Java 8 calculating the difference is more intuitive using LocalDate, LocalDateTime to represent the two dates

        LocalDate now = LocalDate.now();
        LocalDate inputDate = LocalDate.of(2018, 11, 28);
    
        Period period = Period.between( inputDate, now);
        int diff = period.getDays();
        System.out.println("diff = " + diff);
    
    0 讨论(0)
  • 2020-11-22 10:02

    Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:

    Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
    

    It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.

    // 5am on the 20th to 1pm on the 21st, October 2013, Brazil
    DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
    DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
    DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
    System.out.println(daysBetween(start.withTimeAtStartOfDay(),
                                   end.withTimeAtStartOfDay()).getDays());
    // prints 0
    System.out.println(daysBetween(start.toLocalDate(),
                                   end.toLocalDate()).getDays());
    // prints 1
    

    Going via a LocalDate sidesteps the whole issue.

    0 讨论(0)
提交回复
热议问题