Search code examples
javadatecalendardayofweeklocaldate

How to get first and last day in specific week in month


I need help to return the first day (and last day) of a given week, passing only the week of the month and the corresponding month and year.

I've already looked for a way to return using LocalDate or Calendar and haven't found it.

My Locale is PT-BR - First day of week is Sunday

Thanks in advance.

Ex:

Year 2021 - Month 7 (July) - Week 1 - First day: 1 - Last Day: 3
Year 2021 - Month 7 (July) - Week 2 - First day: 4 - Last Day: 10
Year 2021 - Month 7 (July) - Week 3 - First day: 11 - Last Day: 17
Year 2021 - Month 7 (July) - Week 4 - First day: 18 - Last Day: 24
Year 2021 - Month 7 (July) - Week 5 - First day: 25 - Last Day: 31

Solution

  • I found your week calendar approach quite amusing to play with, came up with a method that receives two parameters (month and year) and builds up the week calendar of that month:

    private static Map<Integer, Integer[]> getWeekCalendar(int month, int year) {
        Map<Integer, Integer[]> weekCalendar = new HashMap<>();
        LocalDate date = LocalDate.of(year,month,1);
        int week = 1;
        LocalDate firstOfWeek = LocalDate.from(date);
        while (date.getMonth().equals(Month.of(month))) {
            //if it is a saturday, advance to the next week and register current week bounds
            if (date.getDayOfWeek().equals(DayOfWeek.SATURDAY)) {
                weekCalendar.put(week++, new Integer[]{firstOfWeek.getDayOfMonth(), date.getDayOfMonth()});
                firstOfWeek = LocalDate.from(date.plusDays(1L));
            }
            date = date.plusDays(1L);
        }
        //this one is necessary because the month may end on a Saturday
        if (firstOfWeek.getMonth().equals(Month.of(month))) {
            weekCalendar.put(week, new Integer[]{firstOfWeek.getDayOfMonth(), date.minusDays(1L).getDayOfMonth()});
        }
        return weekCalendar;
    }
    

    And a main class for testing purposes:

    public static void main(String[] args) {
        int wantedMonth = 7;
        int wantedYear = 2021;
        Map<Integer, Integer[]> weekCalendar = getWeekCalendar(wantedMonth, wantedYear);
        weekCalendar.entrySet().stream()
                .map(e -> String.format("Year %d - Month %d (%s) - Week %d - First day: %d - Last day: %d", wantedYear, wantedMonth, Month.of(wantedMonth).name(), e.getKey(), e.getValue()[0], e.getValue()[1]))
                .forEach(System.out::println);
    }
    

    output:

    Year 2021 - Month 7 (JULY) - Week 1 - First day: 1 - Last day: 3
    Year 2021 - Month 7 (JULY) - Week 2 - First day: 4 - Last day: 10
    Year 2021 - Month 7 (JULY) - Week 3 - First day: 11 - Last day: 17
    Year 2021 - Month 7 (JULY) - Week 4 - First day: 18 - Last day: 24
    Year 2021 - Month 7 (JULY) - Week 5 - First day: 25 - Last day: 31