1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
/**
* 获取第一周不允许跨年,但是最后一周允许跨年的自然周开始时间、结束时间
* 输入:2022 1
* 输出:[2022-01-03T00:00, 2022-01-09T23:59:59.999999999]
* 输入:2022 52
* 输出:[2022-12-26T00:00, 2023-01-01T23:59:59.999999999]
*/
@Nonnull
public static LocalDateTime[] getStAndEtAnWeek(@Nonnull Integer year,
@Nonnull Integer week) {
// 传入的那一周的周一和周日
LocalDate startDate = LocalDate.of(year, 1, 1).plusWeeks(week - 1).with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
LocalDate endDate = LocalDate.of(year, 1, 1).plusWeeks(week - 1).with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
// 如果本年第一周的周一落在了上一年, 则将下一周作为本年的第一周
LocalDate firstWeekMonDay = LocalDate.of(year, 1, 1).with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
if (firstWeekMonDay.getYear() < year) {
startDate = startDate.plusWeeks(1);
endDate = endDate.plusWeeks(1);
}
// 如果周一落在了下一年,则传入的周数超出了当前年的范围
if (startDate.getYear() > year) {
throw new IllegalArgumentException("传入的周数超出了当前年的范围");
}
return new LocalDateTime[]{startDate.atTime(LocalTime.MIN), endDate.atTime(LocalTime.MAX)};
}
|