This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: How do you count twoJodaThe number of days between dates?

My requirement is that if the start time is Monday and the end time is Tuesday, the return value should be 1 regardless of the time/minute/second of the start and end dates.

Days.daysbetween (start, end).getDays() If the start time is in the evening and the end time is in the morning, the value is 0.

I have the same problem with other date fields, so I wish there was a universal way to “ignore” the less meaningful fields.

In other words, the months between February and March 4 are also 1, 14:45 and 15:12 time difference 1. But the time difference between 14:01 and 14:55 is 0.

Answer a

Unfortunately, using the withTimeAtStartOfDay method does not work, and occasionally, errors can occur.

You can use the following methods:

Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
Copy the code

“Midnight/the beginning of the day”, which sometimes means 1 am (as daylight saving time does in some places), is a problem that cannot be addressed by the above method.

// 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
Copy the code

Problems can be avoided by using LocalDate.

Answer two

Use java.time.Period to count days

Java8 LocalDate, LocalDateTime to represent these two dates, can be more intuitive calculation of the difference

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);
Copy the code

The article translated from Stack Overflow:stackoverflow.com/questions/3…