2

There are plenty examples of how similar things can be done using Joda-Time and old java.util.Calendar/java.util.Date APIs, but there are no complete examples of how it can be achieved using pure java.time API, without any additional dependencies.

There are also many examples, how to generate dates for the given two dates. But I was unable to found a complete example of how to generate a week dates for a given year and calendar week number.

Could you provide an example of doing this in pure Java 8/java.time API?

Community
  • 1
  • 1
Mateusz Szulc
  • 1,734
  • 19
  • 18

1 Answers1

5

Pure Java 8 / java.time solution

public static List<LocalDate> datesListOfCalendarWeek(int year, long calendarWeek) {
    LocalDate start = LocalDate.ofYearDay(year,1)
            .with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, calendarWeek)
            .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));

    return IntStream.range(0, 7).mapToObj(start::plusDays).collect(toList());
}

Compare with Joda-Time solution:

public static List<org.joda.time.LocalDate> datesListOfCalendarWeek(int year, int calendarWeek) {
    org.joda.time.LocalDate start = new org.joda.time.LocalDate(year,1,1)
            .withWeekOfWeekyear(calendarWeek).withDayOfWeek(1);
    return IntStream.range(0, 7).mapToObj(start::plusDays).collect(toList());
}

And obviously, for any given LocalDate the solutions looks accordingly as follows:

/* Pure Java 8 / java.time */
public static List<LocalDate> datesListOfCalendarWeek(LocalDate date) {
    LocalDate start = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    return IntStream.range(0, 7).mapToObj(start::plusDays).collect(toList());
}

/* Joda-Time */
public static List<org.joda.time.LocalDate> datesListOfCalendarWeek(org.joda.time.LocalDate date) {
    org.joda.time.LocalDate start = date.withDayOfWeek(1);
    return IntStream.range(0, 7).mapToObj(start::plusDays).collect(toList());
}
Mateusz Szulc
  • 1,734
  • 19
  • 18