get Days Of Week Count - Java java.util

Java examples for java.util:Week

Description

get Days Of Week Count

Demo Code


//package com.java2s;

import java.util.Calendar;

import java.util.Date;

public class Main {
    public static void main(String[] argv) throws Exception {
        int dayOfWeek = 2;
        Date date = new Date();
        System.out.println(getDaysOfWeekCount(dayOfWeek, date));
    }//  w  ww. ja  va2 s. c  om

    private static final int DAYS_IN_MONTH[] = { 31, 28, 31, 30, 31, 30,
            31, 31, 30, 31, 30, 31 };

    public static final int getDaysOfWeekCount(int dayOfWeek, Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return getDaysOfWeekCount(dayOfWeek, calendar);
    }

    public static final int getDaysOfWeekCount(int dayOfWeek,
            Calendar calendar) {
        int res = 0;

        boolean isLeapYear = isLeapYear(calendar);
        int daysInMonth = getDaysInMonth(calendar.get(Calendar.MONTH),
                isLeapYear);

        for (int i = 1; i <= daysInMonth; i++) {
            calendar.set(Calendar.DAY_OF_MONTH, i);
            if (dayOfWeek == calendar.get(Calendar.DAY_OF_WEEK)) {
                res++;
            }
        }

        return res;
    }

    private static final boolean isLeapYear(Calendar calendar) {
        int year = calendar.get(Calendar.YEAR);
        return isLeapYear(year);
    }

    private static final boolean isLeapYear(int year) {
        return ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0));
    }

    public static int getDaysInMonth(Calendar calendar) {
        return getDaysInMonth(calendar.get(Calendar.MONTH),
                isLeapYear(calendar));
    }

    public static int getDaysInMonth(int month, boolean isLeapYear) {
        int res = 0;
        if (month >= Calendar.JANUARY && month <= Calendar.DECEMBER) {
            if (isLeapYear && month == Calendar.FEBRUARY) {
                res = 29;
            } else {
                res = DAYS_IN_MONTH[month];
            }
        }

        return res;
    }
}

Related Tutorials