87. Getting the number of weeks between two dates
If the given two dates are instances of LocalDate
(Time
), then we can rely on java.time.temporal.ChronoUnit
. This API exposes a set of units useful to manipulate a date, time, or date-time and we have used it before in Problem 78. This time, let’s use it again to compute the number of weeks between two dates:
public static long nrOfWeeks(
LocalDateTime startLdt, LocalDateTime endLdt) {
return Math.abs(ChronoUnit.WEEKS.between(
startLdt, endLdt));
}
On the other hand, if the given dates are java.util.Date
, then you can choose to convert them to LocalDateTime
and use the previous code or to rely on the Calendar
API. Using the Calendar
API is about looping from the start date to the end date while incrementing the calendar date week by week:
public static long nrOfWeeks(Date startDate, Date endDate) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
int weeks = 0;
while (calendar...