How do I count occurrence of a day between two dates?

The code below helps you to find the number occurrence of a day between two specified date. The solution used below it to loop between the two dates and check if the weekday of those dates are equals to the day the occurrence 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(2000, 0, 1);
        Calendar end = Calendar.getInstance();
        end.set(2009, 11, 31);

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

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

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

        System.out.println(numberOfDays);
    }
}

The result of our program is:

Number mondays of between Sat Jan 01 13:48:51 CST 2000 and Thu Dec 31 13:48:51 CST 2009 are: 522

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply