Get Calendar Week Difference Between Local Dates

JCamacho :

I'm having trouble finding a post where the solution is something else besides

Get day difference and divide by 7

I'm looking to get the difference in calendar weeks between two dates, where the weeks start on Mondays.

For instance, the number of weeks between Nov 4th, 2019 and Nov 10th, 2019 should be 0.

However, the number of weeks between Nov 10th, 2019 and Nov 11th, 2019 should be 1.

The solution should also account for dates in different years. Any solutions that use LocalDate?

assylias :

ChronoUnits have a between method which returns the number of complete units between a start and end date/time. To count weeks Monday to Sunday, you could "round down" your dates to the previous Monday. In your case it could look like this:

LocalDate start = LocalDate.of(2019, 11, 10);
LocalDate end = LocalDate.of(2019, 11, 11);

LocalDate mondayStart = start.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDate mondayEnd = end.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));

System.out.println(ChronoUnit.WEEKS.between(mondayStart, mondayEnd));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322113&siteId=1