Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Calendar Week Difference Between Local Dates

Tags:

java

kotlin

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?

like image 789
JCamacho Avatar asked Mar 03 '23 05:03

JCamacho


2 Answers

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));
like image 79
assylias Avatar answered Mar 13 '23 06:03

assylias


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);
like image 45
SQL Hacks Avatar answered Mar 13 '23 08:03

SQL Hacks