Determining the Number of Days in a Month

GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar system used by most of the world.

GregorianCalendar is a hybrid calendar that supports both the Julian and Gregorian calendar systems with the support of a single discontinuity

Constructor for GregorianCalendar looks like :

GregorianCalendar(year, Calendar.FEBRUARY, 1):
Year and month are specified in the constructor to create instance for finding the number of days in that month of the specified year.

GregorianCalendar the constructor takes three arguments as follows:

* First is the year.
* Second is the month Ex. February.
* And third is the initial date value.

Calendar.getActualMaximum(Calendar.DAY_OF_MONTH) - Returns the maximum date value in the specified month of the specific year. It returns a integer value.

package com.anuj.basic;

import java.util.*;
import java.io.*;

public class GettingDaysInMonth {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        int year = 1;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter year : ");       
        try {
          year = Integer.parseInt(in.readLine());
          if (year < 1900 || year > 2100) {
           System.out.println("Enter year greater than 1900 and less than 2100");
           System.exit(0);
          }
        } catch (NumberFormatException ne) {
          System.out.print(ne.getMessage() + " is not a valid entry.");
          System.out.println("Please enter a four digit number.");
          System.exit(0);
        }
    
        Calendar cal = new GregorianCalendar(year, Calendar.FEBRUARY, 1);
        int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        System.out.print("Number of days : " + days);
    }
}
Output :

Enter year : 2012
Number of days : 29

No comments:

Post a Comment