GregorianCalendar in java

GregorianCalendar is a concrete implementation of a Calendar that implements the normal Gregorian calendar with which you are familiar. The getInstance( ) method of Calendar will typically return a GregorianCalendar initialized with the current date and time in the default locale and time zone

GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar.

There are also several constructors for GregorianCalendar objects. The default, GregorianCalendar( ), initializes the object with the current date and time in the default locale and time zone. Three more constructors offer increasing levels of specificity:

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)

All three versions set the day, month, and year. Here, year specifies the year. The month is specified by month, with zero indicating January. The day of the month is specified by dayOfMonth. The first version sets the time to midnight. The second version also sets the hours and the minutes. The third version adds seconds.

GregorianCalendar(Locale locale)

GregorianCalendar(TimeZone timeZone)

GregorianCalendar(TimeZone timeZone, Locale locale)

Demonstrate GregorianCalendar

import java.util.*;

class GregorianCalendarDemo {

public static void main(String args[]) { String months[] = {

"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

int year;

//Create a Gregorian calendar initialized

//with the current date and time in the

//default locale and timezone.

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

}

}

}

Output

Date: Jan 1 2007

Time: 11:25:27

The current year is not a leap year

Leave a Comment