I'm trying to figure out how to determine whether a particular Monday is the first, second, third or fourth Monday of a given month. I've figured out how to get the next Monday and the Week of the of month that resides in using the LocalDate class.
LocalDate now = LocalDate.of(2018, 2, 1);
LocalDate nextMonday = now.with(next(DayOfWeek.MONDAY));
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int week = nextMonday.get(weekFields.weekOfMonth());
Case in the example above, the code gets the next Monday and the week it resides in. Week is the second week of Feb, but that Monday is not the second Monday, it's the first. Any help with this would be greatly appreciated.
Edit: You should take the answer by Anonymous (ChronoField.ALIGNED_WEEK_OF_MONTH
) instead of this answer.
You could figure out what day of the month it is, divide by 7, and add 1:
LocalDate nextMonday = now.with(next(DayOfWeek.MONDAY));
int weekNo = ((nextMonday.getDayOfMonth()-1) / 7) +1;
For example, this code:
LocalDate now = LocalDate.of(2018, 2, 1);
for(int i = 0; i < 10; i++) {
now = now.with(next(DayOfWeek.MONDAY));
int weekNo = ((now.getDayOfMonth()-1) / 7) +1;
System.out.println("Date : " + now + " == " + weekNo);
}
Prints out the following, which is what I believe you want...
Date : 2018-02-05 == 1
Date : 2018-02-12 == 2
Date : 2018-02-19 == 3
Date : 2018-02-26 == 4
Date : 2018-03-05 == 1
Date : 2018-03-12 == 2
Date : 2018-03-19 == 3
Date : 2018-03-26 == 4
Date : 2018-04-02 == 1
Date : 2018-04-09 == 2