plenty examples使用 Joda-Time 和旧 java.util.Calendar / java.util.Date API,但没有关于如何使用纯 java.time API实现它的完整示例,没有任何其他依赖项。
还有很多例子,如何为给定的两个日期生成日期。但我无法找到如何生成给定年份和日历周数的周日期的完整示例。
您能否提供一个在纯 Java 8 / java.time API中执行此操作的示例?
答案 0 :(得分:3)
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());
}
与Joda-Time解决方案比较:
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());
}
显然,对于任何给定的LocalDate,解决方案的内容如下:
/* 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());
}