How do I count number of weekday between two dates?

The code below helps you to find the number of a specified weekday (Monday, Tuesday, Wednesday, etc) between two dates. The solution we used below is to loop between the two dates and check if the weekday of those dates are equals to the day we want to count.

package org.kodejava.example.util;

import java.util.Calendar;

public class DaysBetweenDate {
    public static void main(String[] args) {
        // Month value in Java is 0-based so 11 means December.
        Calendar start = Calendar.getInstance();
        start.set(2017, 11, 1);
        Calendar end = Calendar.getInstance();
        end.set(2017, 11, 31);

        System.out.print("Number Monday between " +
            start.getTime() + " and " + end.getTime() + " are: ");

        int numberOfDays = 0;
        int monday = Calendar.MONDAY;

        while (start.before(end)) {
            if (start.get(Calendar.DAY_OF_WEEK) == monday) {
                numberOfDays++;
                start.add(Calendar.DATE, 7);
            } else {
                start.add(Calendar.DATE, 1);
            }
        }

        System.out.println(numberOfDays);
    }
}

The result of our program is:

Number Monday between Fri Dec 01 15:57:12 CST 2017 and Sun Dec 31 15:57:12 CST 2017 are: 4

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply