我想获取 2 个日期之间的所有周,其中跨 2 个月的周每个月计算两次。例如,2021 年的第 14 周同时举办了 3 月和 4 月,因此在这种情况下,我希望该周计算两次(一次为 3 月,一次为 4 月)。我查看并发现只有一些库可以计算两个日期之间的周数。我想我可以得到周数和月份数并形成一个独特的数组,但这似乎有点过头了。有人有什么建议吗?
最佳答案
weeks that cross 2 months counted twice
下面的代码允许仅使用标准 LocalDate
类及其方法 isBefore()
、plusWeeks()
、plusDays()
.
请记住,星期几和月份由java.time
中的枚举表示包。
我做了一些假设:
- 一周从星期日开始;
- 必须考虑给定期间开始和结束的一周中的部分内容以及完整的周。
public static void main(String[] args) {
System.out.println(getWeekCount(LocalDate.of(2022, 1, 1),
LocalDate.of(2022, 2, 1)));
System.out.println(getWeekCount(LocalDate.of(2022, 1, 1),
LocalDate.of(2022, 3, 1)));
}
public static int getWeekCount(LocalDate date1, LocalDate date2) {
int weekCount = 0;
LocalDate cur = date1;
LocalDate finish = date2;
// assumption: week starts with sunday
// assumption: chunk of week at the start and at the end have to be taken into account as well as full weeks
if (cur.getDayOfWeek() != DayOfWeek.SUNDAY) { // adjusting current date
LocalDate next = cur.plusDays(DayOfWeek.SUNDAY.ordinal() - cur.getDayOfWeek().ordinal() + 1);
weekCount += getWeeksIncrement(cur, next);
cur = next;
}
if (finish.getDayOfWeek() != DayOfWeek.SUNDAY) { // adjusting finish date
LocalDate previous = finish.minusDays(finish.getDayOfWeek().ordinal() + 1);
weekCount += getWeeksIncrement(previous, finish);
finish = previous;
}
while (cur.isBefore(finish) || cur.equals(finish)) {
LocalDate next = cur.plusWeeks(1);
weekCount += getWeeksIncrement(cur, next);
cur = next;
}
return weekCount;
}
public static int getWeeksIncrement(LocalDate cur, LocalDate next) {
return weekIsSharedBetweenTwoMonth(cur, next) ? 2 : 1;
}
public static boolean weekIsSharedBetweenTwoMonth(LocalDate cur, LocalDate next) {
return next.getMonth() != cur.getMonth() &&
next.withDayOfMonth(1).isAfter(cur);
}
输出
7 - weeks between: 2022-01-01 and 2022-02-01
12 - weeks between: 2022-01-01 and 2022-03-01
关于java - 获取 2 个日期之间的周数,其中周数跨越 2 个月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71307750/