如何使用joda时间排除日期范围内的周末

时间:2015-04-16 11:43:57

标签: java jodatime

我试图找到使用joda时间的工作日。但是这里我遇到了一个问题,那就是4月它没有给出正确的结果。我发布了代码以及我从代码中获得的输出..

public class ExcludingWeekEnds {

public static List<LocalDate> dateList = new ArrayList<LocalDate>();
public static void main(String[] args) {
    final LocalDate start = new LocalDate(2015,4,1);
    final LocalDate end = new LocalDate(2015, 4, 30);


    LocalDate weekday = start;

    if (start.getDayOfWeek() == DateTimeConstants.SATURDAY ||
            start.getDayOfWeek() == DateTimeConstants.SUNDAY) {
        weekday = weekday.plusWeeks(1).withDayOfWeek(DateTimeConstants.MONDAY);
    }

    while (weekday.isBefore(end)) {
        System.out.println(weekday);
        dateList.add(weekday);

        if (weekday.getDayOfWeek() == DateTimeConstants.FRIDAY)
            weekday = weekday.plusDays(3);
        else
            weekday = weekday.plusDays(1);
    }

    System.out.println(dateList.size());
}
} 

这是我得到的输出

2015-04-01
2015-04-02
2015-04-03
2015-04-06
2015-04-07
2015-04-08
2015-04-09
2015-04-10
2015-04-13
2015-04-14
2015-04-15
2015-04-16
2015-04-17
2015-04-20
2015-04-21
2015-04-22
2015-04-23
2015-04-24
2015-04-27
2015-04-28
2015-04-29
21

有人帮助我

1 个答案:

答案 0 :(得分:3)

正如马文在评论中所说,你应该修改你的条件:

while (!weekday.isAfter(end)) { // Modify HERE
    System.out.println(weekday);
    dateList.add(weekday);

    if (weekday.getDayOfWeek() == DateTimeConstants.FRIDAY)
        weekday = weekday.plusDays(3);
    else
        weekday = weekday.plusDays(1);
}

所以你可以得到结果,包括结尾。