Java GregorianCalendar class

Introduction

GregorianCalendar is an implementation of a Calendar.

It implements the normal Gregorian calendar.

The Calendar.getInstance() method typically returns a GregorianCalendar initialized with the current date and time in the default locale and time zone.

GregorianCalendar defines two fields: AD and BC.

You can use the following constructors to create GregorianCalendar.

GregorianCalendar(int year, int month, int dayOfMonth)  
GregorianCalendar(int year, int month, int dayOfMonth, int hours,  
                  int  minutes)  
GregorianCalendar(int year, int month, int dayOfMonth, int hours,  
                  int  minutes, int seconds) 

The following program demonstrates GregorianCalendar:


// Demonstrate GregorianCalendar
import java.util.Calendar;
import java.util.GregorianCalendar;

public class Main {
  public static void main(String args[]) {
    String months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
    int year;/*from   w ww  .jav  a  2s  .  co m*/

    // Create a Gregorian calendar initialized
    // with the current date and time in the
    // default locale and time zone.
    GregorianCalendar gcalendar = new GregorianCalendar();

    // Display current time and date information.
    System.out.print("Date: ");
    System.out.print(months[gcalendar.get(Calendar.MONTH)]);
    System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
    System.out.println(year = gcalendar.get(Calendar.YEAR));

    System.out.print("Time: ");
    System.out.print(gcalendar.get(Calendar.HOUR) + ":");
    System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
    System.out.println(gcalendar.get(Calendar.SECOND));

    // Test if the current year is a leap year
    if (gcalendar.isLeapYear(year)) {
      System.out.println("The current year is a leap year");
    } else {
      System.out.println("The current year is not a leap year");
    }
  }
}



PreviousNext

Related