GregorianCalendar
In this chapter you will learn:
GregorianCalendar class
GregorianCalendar is a concrete implementation of a Calendar for Gregorian calendar. It defines two fields, AD and BC, to represent the two eras defined by the Gregorian calendar.
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.
- year specifies the number of years that have elapsed since 1900.
- month is specified by month, with zero indicating January.
- day of the month is specified by dayOfMonth.
The following constructors create objects initialized with the current date and time using the specified time zone and/or locale:
GregorianCalendar(Locale locale)
GregorianCalendar(TimeZone timeZone)
GregorianCalendar(TimeZone timeZone, Locale locale)
isLeapYear( ) method frolm the GregorianCalendar class tests if the year is a leap year.
Its form is
boolean isLeapYear(int year)
Using GregorianCalendar
The following program demonstrates GregorianCalendar:
import java.util.Calendar;
import java.util.GregorianCalendar;
/*from j a v a 2 s.c o m*/
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;
// 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(months[gcalendar.get(Calendar.MONTH)]);
System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
System.out.println(year = gcalendar.get(Calendar.YEAR));
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");
}
}
}
Sample output is shown here:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Date, Time, Calendar, TimeZone