How to get daterange by having week number of the month and the year in Java? [closed]

Assuming we have data "September2021W5", in which W5 is the week number of the month September2021. Ofcourse I can write custom method to split and get year, month and week-number of the month seperately. How can we get daterange i.e start date and end date of that particular week. I had checked other similar questions but they all had it solved in case of weeknumber specified for the year and not month. Thanks in advance for any guidance or help provided!!!


Solution 1:

Build a DateTimeFormatter that uses a default day of week as needed (start of week, e.g. Monday).
Example:

var format = new DateTimeFormatterBuilder()
             .appendPattern("MMMMuuuu'W'W")   // or use corresponding appends
             .parseDefaulting(ChronoField.DAY_OF_WEEK, DayOfWeek.MONDAY.getValue())
             .toFormatter()
             .withLocale(Locale.US);
var date = LocalDate.parse("September2021W5", format);

same can be done for the end of the week, or just adding 6 days to previous result (date.plusDays(6))


MMMM is for month of year, full form
uuuu year
'W' for literal W
W for week of month

Using Locale.UK so the month gets parsed for that locale, use the one needed for the given input - to use the default system Locale, use Locale.getDefault().