您需要知道每年的周数,这样您就可以确定您的条件是在奇数周还是偶数周内启用。您不能只计算今年或去年一年中的周数是偶数还是奇数,因为它基本上是累积的。
如果您只需要在有限的日期范围内(例如 2000 到 2100),那么您可以只计算一个表格。如果您在非常广泛的日期范围内需要它,您可以建立一个 400 年的表格,并利用每 400 年循环一次的所有内容。
java.time
使用API的更简单情况的示例:
例如:
private static final int MIN_YEAR_INCLUSIVE = 2000;
private static final int MAX_YEAR_EXCLUSIVE = 2100;
private static final boolean[] ENABLED_FOR_ODD_WEEKS =
buildTable(MIN_YEAR_INCLUSIVE, MAX_YEAR_EXCLUSIVE);
private static final boolean[] buildTable(int minYear, int maxYear) {
boolean[] table = new boolean[maxYear - minYear];
boolean current = true;
for (int year = minYear; year < maxYear; year++) {
table[year - minYear] = current;
Year accessor = Year.of(year);
int weeksInYear = IsoFields
.WEEK_OF_WEEK_BASED_YEAR
.rangeRefinedBy(accessor)
.getMaximum();
if (weeksInYear == 53) {
current = !current;
}
}
}
public boolean isEnabled(LocalDate date) {
int year = date.getYear();
if (year < MIN_YEAR_INCLUSIVE || year >= MAX_YEAR_EXCLUSIVE) {
throw new IllegalArgumentException("Invalid year: " + year);
}
int weekOfWeekYear = date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
boolean oddWeek = weekOfWeekYear % 2 == 1;
return oddWeek == ENABLED_FOR_ODD_WEEKS[year - MIN_YEAR_INCLUSIVE];
}