get Days In Month - Java java.util

Java examples for java.util:Month

Description

get Days In Month

Demo Code


//package com.java2s;

import java.util.Calendar;

public class Main {
    public static void main(String[] argv) throws Exception {
        Calendar calendar = Calendar.getInstance();
        System.out.println(getDaysInMonth(calendar));
    }/*from  ww  w .j  a  v  a2 s .  com*/

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

    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;
    }

    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));
    }
}

Related Tutorials