Mohamed Gabr
Mohamed Gabr

Reputation: 441

Java Calendar: I want to remove specific Day of week from calendar

More details I want to get rid of specific days of the week.

I mean like: {Sat(1), Sun(2), Mon(3) , Tues(4) , Wed (5),Thurs(6) ,Fri(7)}.

Remove Week Days: {Sat(1), Sun(2), Mon(3) , Tues(4) , Wed (5)}.

So I can get the Count of days without the excluded days from the specific start date to the date of now.

Hint: I must Use the Java Calendar

The problem is specifying the day dynamically

Upvotes: 1

Views: 1119

Answers (1)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22635

If you can use LocalDate and stream you can apply a functional approach.

LocalDate start = LocalDate.of(2015, 2, 1);
LocalDate end = LocalDate.of(2015, 2, 28);

List<DayOfWeek> includedDays = Arrays.asList(DayOfWeek.THURSDAY, DayOfWeek.FRIDAY);

long daysCount = Stream.iterate(start, date -> date.plusDays(1))
        .limit(ChronoUnit.DAYS.between(start, end))
        .filter(d -> includedDays.contains(d.getDayOfWeek()))
        .count();

If you insist on calendar just use:

GregorianCalendar calendarStart = new GregorianCalendar(2015, 2, 1);
GregorianCalendar calendarEnd = new GregorianCalendar(2015, 2, 28);

List<Integer> includedDays = Arrays.asList(GregorianCalendar.THURSDAY, GregorianCalendar.FRIDAY);
long count = 0;
while(!calendarStart.equals(calendarEnd)) {
    if(includedDays.contains(calendarStart.get(Calendar.DAY_OF_WEEK))) {
        count ++;
    }
    calendarStart.add(Calendar.DATE, 1);
}

Upvotes: 6

Related Questions