lucifer
lucifer

Reputation: 2327

How to exclude the weekends in a date range using joda time

I am trying to find the business days using joda time.But here i am getting one problem ,that for april it is not giving the correct result. I a posting the code and also the output i am getting from my code..

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());
}
} 

And here is the output i am getting

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

Somebody help me

Upvotes: 1

Views: 3404

Answers (1)

Qianyue
Qianyue

Reputation: 1777

As Marvin says in the comment, you should modify your condition while :

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);
}

So you can get the result including the end.

Upvotes: 4

Related Questions