Search code examples
javadatejava-8calendardate-range

Is it posibile to split a daterange in Java into weeks?


My Problem is the folowing: I have a daterange (in java), specified by two Calendar objects, one for the start, one for the end. Now I want to get an List of all weeks which are in this range. A week should be specified by two Calendar objects, also one for the start and one for the end. It is also important, that the start and the end of the whole daterange could be in two different months or even two different years.


Solution

  • Here is implementation of your problem which using new Time Api, read about LocalDate, LocalDateTime, Period etc.

            LocalDate startDate = LocalDate.of(2019, 12, 12).with(DayOfWeek.MONDAY);
            LocalDate endDate = LocalDate.of(2020, 12, 12);
    
            //number of weeks
            long weekNumber = ChronoUnit.WEEKS.between(startDate, endDate);
    
            Map<LocalDate, LocalDate> weeks = new LinkedHashMap<>();
            for (int i = 0; i < weekNumber; i++) {
                LocalDate endOfWeek = startDate.plusDays(6);
                weeks.put(startDate, endOfWeek);
                startDate = endOfWeek.plusDays(1);
            }
            for (LocalDate week : weeks.keySet()) {
                LocalDate endOfWeek = weeks.get(week);
                System.out.println("Start of week: " + week + "[" + week.getDayOfWeek() + "]" +
                        " End of week: " + endOfWeek + "[" + endOfWeek.getDayOfWeek() + "]");
            }
    

    It prints:

    Start of week: 2020-12-07[MONDAY] End of week: 2020-12-13[SUNDAY]
    Start of week: 2020-12-14[MONDAY] End of week: 2020-12-20[SUNDAY]
    Start of week: 2020-12-21[MONDAY] End of week: 2020-12-27[SUNDAY]
    Start of week: 2020-12-28[MONDAY] End of week: 2021-01-03[SUNDAY]
    Start of week: 2021-01-04[MONDAY] End of week: 2021-01-10[SUNDAY]
    

    etc...

    edit:

    With DateTimeFormatter will be even shorter and day name will display in your language:

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd[EEEE]");
    for (LocalDate startOfWeek : weeks.keySet()) {
        LocalDate endOfWeek = weeks.get(startOfWeek);
        System.out.println("Start of week: " + dateTimeFormatter.format(startOfWeek) +
                        " End of week: " + dateTimeFormatter.format(endOfWeek));
        }