感謝大家,這是一個能夠滿足我的要求的工作解決方案(請注意,在大多數情況下添加7天到大多數情況下都不會產生日曆周,只有當它是星期一!) 此代碼使用Joda Time API 。
private static List<Interval> getWeeks(final DateTime start, final DateTime finish)
{
final int weekLeaps = Weeks.weeksBetween(start, finish).getWeeks();
if (weekLeaps == 0) {
return ImmutableList.of(new Interval(start, finish));
} else {
// We hop sundays at least once
final ImmutableList.Builder<Interval> resBuild = ImmutableList.<Interval> builder();
// First week
DateTime wStart = start;
DateTime wEnd = rollToWeekEnd(start);
resBuild.add(new Interval(wStart, wEnd));
// Other weeks
for (int i = 0; i < weekLeaps; i++) {
wStart = wEnd.plusSeconds(1);
DateTime actWeekEnd = rollToWeekEnd(wStart);
wEnd = actWeekEnd.isBefore(finish) ? actWeekEnd : finish;
resBuild.add(new Interval(wStart, wEnd));
}
return resBuild.build();
}
}
private static DateTime rollToWeekEnd(final DateTime from)
{
return from.withDayOfWeek(DateTimeConstants.SUNDAY)
.withHourOfDay(23)
.withMinuteOfHour(59)
.withSecondOfMinute(59)
.withMillisOfSecond(0);
}
你在這裏有什麼問題? –
問題是,如何在Java中實現這一點。 – gyorgyabraham
好的。你可以請一個例子解釋一下,這樣會更清楚。 –