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
?
ChronoUnit
s 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));
I would start with a known Monday and calculate the week number counting from then. 1st Jan 1962 was a Monday (other Mondays are available).
LocalDate knownMonday = LocalDate.of(1962,1,1);
LocalDate start = LocalDate.of(2019, 11, 10);
LocalDate end = LocalDate.of(2019, 11, 11);
long sWeek = (long)Math.floor(knownMonday.until(start,ChronoUnit.DAYS)/7.0);
long lWeek = (long)Math.floor(knownMonday.until(end ,ChronoUnit.DAYS)/7.0);
System.out.println(lWeek-sWeek);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With