我怎样才能找到2个日期之间的周末数

时间:2016-12-16 15:40:31

标签: java

我的问题是以下我需要知道两个日期之间有多少个星期结束。 由于我对我的解决方案不满意,所以我四处询问。

int numberOfWeekendContained(LocalDate start, LocalDate end) {
    int weekends = 0;
    for (LocalDate day = startTime.toLocalDate(); !day.isAfter(end); day = day.plusDays(1)) {
        LocalDate previousDay = day.minusDays(1);
        if (isWeekEnd(day) && (!isWeekEnd(previousDay) || !isInRange(previousDay, start, end))) {
            weekends++;
        }
    }
    return weekends;
}

private static boolean isWeekEnd(LocalDate day) {
    return DayOfWeek.SATURDAY.equals(day.getDayOfWeek()) || DayOfWeek.SUNDAY.equals(day.getDayOfWeek());
}

private static boolean isInRange(LocalDate day, LocalDate start, LocalDate end) {
    return !day.isBefore(start) && !day.isAfter(end);
}

周日或周六计为整个周末。即,如果我的范围从星期日到星期一,我有1个周末。如果从星期日到下周六,则计为2。

我真的不喜欢在我看来是乍看之下难以理解的。

有谁知道如何让这个更干净?

2 个答案:

答案 0 :(得分:2)

我认为这就是诀窍:

public static int numberOfWeekendContained(LocalDate start, LocalDate end) {
    LocalDate firstMondayAfterStart = start.plusDays(8-start.getDayOfWeek().getValue());
    LocalDate lastSundayBeforeEnd = end.minusDays(end.getDayOfWeek().getValue());

    int numberOfWeeksInbetween = Math.floorDiv(Period.between(firstMondayAfterStart, lastSundayBeforeEnd).getDays() + 1, 7);

    return 
        Math.max(0, Math.min(2, 7 - start.getDayOfWeek().getValue())) +     // weekend days from the start week
        Math.max(0, end.getDayOfWeek().getValue() - 5) +                    // weekend days from the end week
        numberOfWeeksInbetween * 2;                                         // weekend days from the weeks inbetween

}

您可以尝试here

答案 1 :(得分:0)

坦克你们所有人的意见。我选择Quintium的解决方案,我觉得它更清晰。即,

int numberOfWeekendContained(LocalDate startDate, LocalDate endDate) {
    LocalDate start = startDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    LocalDate end = endDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY));
    return Period.between(start, end).getDays()/ DAYS_PER_WEEK;
}

DAY_PER_WEEK = 7是常数。不幸的是我在Java 8中找不到Joda Days.DAY_PER_WEEK等价物