Can someone suggest the logic to find out the no. of Mondays between two dates in Java?
Instead of looping through all the days, is there any other approach to count the no. of occurrences of Mondays between two dates in java
Can someone suggest the logic to find out the no. of Mondays between two dates in Java?
Instead of looping through all the days, is there any other approach to count the no. of occurrences of Mondays between two dates in java
There’s more than one way to go. Here’s a suggestion:
public static long noOfMondaysBetween(LocalDate first, LocalDate last) {
if (last.isBefore(first)) {
throw new IllegalArgumentException("first " + first + " was after last " + last);
}
// find first Monday in interval
LocalDate firstMonday = first.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
// similarly find last Monday
LocalDate lastMonday = last.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
// count
long number = ChronoUnit.WEEKS.between(firstMonday, lastMonday);
// add one to count both first Monday and last Monday in
return number + 1;
}
For example, noOfMondaysBetween(LocalDate.of(2017, Month.JUNE, 15), LocalDate.of(2017, Month.JUNE, 15))
returns 0. It may be a little subtle that the code takes this case into account: First Monday is June 19 and last is June 12. Count of weeks between the two Mondays is -1, so when I add 1, the result is 0, which is correct. To count the Mondays in June:
System.out.println(noOfMondaysBetween(LocalDate.of(2017, Month.MAY, 31), LocalDate.of(2017, Month.JULY, 1)));
Result:
4
If you intended to include the first date in the count (if it is a Monday), use nextOrSame(DayOfWeek.MONDAY)
instead of next(DayOfWeek.MONDAY)
. Similarly to include the second date use previousOrSame(DayOfWeek.MONDAY)
.
I'm not a Java coder but I'm a coder. Here's how I'd solve this:
Count the days between the two dates (aka DATESPAN
). I'm sure Java has a function for that.
Get the 'Day of Week' (AS A NUMBER, assuming that Monday = 1 )of both dates. I'm sure Java has a function for this too. We need to know if either is a Monday.
If DATESPAN < 7
Use this logic:
Answer = End Date Number > DATESPAN ? 0 : 1
IF DATESPAN >=7
CONTINUE TO GET ANSWER:
Divide the DATESPAN
by 7.
If there is a remainder from the division, use the floor value of the quotient for the answer.
If there is NO remainder, check the start date and end date. If either are a Monday the quotient is the answer, If not the quotient - 1 is the answer