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

Category: java.util, viewed: 335 time(s).

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
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats