Java Calendar Class
Calendar class in Java is an abstract super class that is designed to support different kinds of calendar systems. It is used to know system data and time information.
Java Calendar class provides some specific functionality that is common to most calendar systems and makes that functionality available to the subclasses.
The subclasses of Calendar class are used to calculate calendar related information (such as second, minute, hour, day of month, month, year, and so on) of a particular calendar system.
For example, a GregorianCalendar is a subclass of the Java Calendar class that is used to determine the day of week of January 15, 2021, in the Gregorian calendar system.
The calendar class was introduced in Java 1.1 version. The calendar API is present in java.util.Calendar. Java 1.4 version introduced the Thai Buddhist Calendar that is a subclass of calendar class. In Java 6, JapaneseImperialCalendar was introduced which is also a subclass Calendar.
Java Calendar Class Declaration
The abstract Calendar class extends Object class and implements Serializable, Cloneable, and Comparable interfaces. The general declaration of calendar class in Java programming is as follows:
public abstract class Calendar
extends Object
implements Serializable, Cloneable, Comparable<Calendar>
Constructors of Java Calendar Class
Calendar class in Java does not provide any public constructor. It provides constructors with protected access modifier that cannot be used outside the package. They are:
1. protected Calendar(): This form of constructor is used by subclass to construct a Calendar with the default time zone and locale.
2. protected Calendar(TimeZone zone, Locale aLocale): This form of constructor is used by subclass to construct a calendar with the specified time zone and locale.
How to Create a Calendar in Java?
To create an object of Calendar class in Java, we need to call getInstance() method. Since this method is static in nature so we call it using Calendar class name like this:
Calendar cl = Calendar.getInstance();
This Calendar object stores the current system date and time by default.
Methods of Calendar Class in Java
Calendar class provides a set of methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. Some commonly used methods defined by Calendar are as follows:
1. abstract void add(int field, int amount): This method is used to add or subtract the specified amount of time to the given calendar field, based on the calendar’s rules.
2. boolean after(Object calendarObj): This method returns true if the invoking calendar object contains a date that is after (later) than specified calendarObj. Otherwise, it returns false.
3. boolean before(Object calendarObj): This method returns true if the invoking calendar object contains a date that is before (earlier) than specified calendarObj. Otherwise, it returns false.
4. final void clear(): It sets zeros all time components in the invoking calendar object.
5. final void clear(int field): It sets zeros the specified time components in the invoking calendar object.
6. Object clone(): It creates and returns a duplicate copy of invoking object.
7. int compareTo(Calendar anotherCalendar): It is used to compare the time values (milliseconds offsets) between two Calendar objects.
8. boolean equals(Object calendarObj): It is used to compare between invoking calendar object and the specified Object calendarObj. It returns true if they are the same. Otherwise, returns false.
9. protected void complete(): This method fills in any unset fields in the calendar fields.
10. protected abstract void computeFields(): This method converts the current millisecond time value time to calendar field values in fields[ ].
11. protected abstract void computeTime(): This method is used to convert the current calendar field values in fields[ ] to the millisecond time value time.
12. int get(int calendarField): It returns the value of the given calendar field.
13. int getActualMaximum(int calendarField): It is used to get the actual maximum value of the calendar field passed as the parameter to getActualMaximum() method.
14. int getActualMinimum(int calendarField): It is used to get the actual minimum value of the calendar field passed as the parameter to getActualMaximum() method.
15. static Locale[ ] getAvailableLocales(): It returns an array of available Locale objects that contains locales for which calendars are available.
16. String getDisplayName(int field, int style, Locale locale): It returns the string representation of the calendar field value in the given style and locale.
17. int getFirstDayOfWeek(): It is used to get the first day of the week integer form. For example, SUNDAY in India., MONDAY in USA.
18. static Calendar getInstance(): It is used to get a calendar object for the default time zone and locale.
19. static Calendar getInstance(Locale locale): It is used to get the calendar object with the specified locale and default time zone.
20. static Calendar getInstance(TimeZone zone): It is used to get a calendar object with the specified time zone and default locale.
21. static Calendar getInstance(TimeZone zone, Locale locale): It returns a calendar object with the specified time zone and locale.
22. final Date getTime(): It returns a Date object that is equal to the time of invoking object.
23. long getTimeInMillis(): It returns time value of calendar in milliseconds.
24. TimeZone getTimeZone(): It is used to get the time zone for the invoking object.
25. int getWeeksInWeekYear(): It is used to get the total number of weeks in the week year represented by the Calendar.
26. int getWeekYear(): It returns the week year represented by the Calendar.
27. int hashCode(): It returns the hash code value for the calendar.
28. final boolean isSet(int field): It returns true if the specified time component of the given calendar is set otherwise, returns false.
29. boolean isWeekDateSupported(): It returns true if the Calendar supports week dates.
30. void set(int field, int value): It sets the date or time component specified by calendar field to the given value in the invoking object.
31. void set(int year, int month, int date): It sets year, month, and day_of_month for a given calendar.
32. void set(int year, int month, int date, int hourOfDay, int minute): It sets the values for the calendar fields such as year, month, day, hour, and minute.
33. void set(int year, int month, int date, int hourOfDay, int minute, int second): It sets the values for the calendar fields like year, month, day, hour, minute, and second.
34. void setFirstDayOfWeek(int value): It sets the first day of the week for a given calendar.
35. void setTime(Date date): It sets the time for the specified calendar object with the given Date.
36. void setTimeInMillis(long millis): It sets the current time in milliseconds for the given calendar object.
37. void setTimeZone(TimeZone value): It sets the time zone for invoking object with the given time zone value.
38. String toString(): It returns a string representation of the given calendar object.
Calendar Field Constants
Calendar class defines the following int constants that are used to get or set components of the calendar. They are listed in the table.
ALL_STYLES | FRIDAY | PM | AM |
HOUR | SATURDAY | AM_PM | HOUR_OF_DAY |
SECOND | APRIL | JANUARY | SEPTEMBER |
AUGUST | JULY | SHORT | DATE |
JUNE | SUNDAY | DAY_OF_MONTH | LONG |
THURSDAY | DAY_OF_WEEK | MARCH | TUESDAY |
DAY_OF_WEEK_IN_MONTH | MAY | UNDECIMBER | DAY_OF_YEAR |
MILLISECOND | WEDNESDAY | DECEMBER | MINUTE |
WEEK_OF_MONTH | DST_OFFSET | MONDAY | WEEK_OF_YEAR |
ERA | MONTH | YEAR | FEBRUARY |
NOVEMBER | ZONE_OFFSET | FIELD_COUNT | OCTOBER |
Instance Variables of Calendar
Java Calendar class defines several protected instance variables that are as follows:
1. areFieldsSet: It is a variable of type boolean that indicates if the time components have been set.
2. fields: It is an array of type ints that stores the components of the time.
3. isSet: It is a variable of type boolean array that indicates if a specific time component has been set.
4. time: It is a variable of type long that stores the current time for the object.
5. isTimeSet: It is a boolean variable that indicates if the current time has been set.
Java Calendar Example Programs
Let’s take some important example programs based on the Java calendar methods.
Example 1: Write a Java program where we will display the system date and time. Look at the program code to understand better.
import java.util.Calendar;
public class CalendarDemo {
public static void main(String[] args)
{
// Create a calendar class object and initialized with the current date and time in the default locale and timezone.
Calendar cl = Calendar.getInstance();
// Display current date information separately.
System.out.print("Current System Date: ");
int dd = cl.get(Calendar.DATE);
int mm = cl.get(Calendar.MONTH);
++mm;
int yy = cl.get(Calendar.YEAR);
System.out.println(dd+ "-" +mm+ "-" +yy);
// Display time information.
System.out.print("Current System Time: ");
int hr = cl.get(Calendar.HOUR);
int min = cl.get(Calendar.MINUTE);
int sec = cl.get(Calendar.SECOND);
int secMilli = cl.get(Calendar.MILLISECOND);
System.out.println(hr+ ":"+min+ ":"+ sec+ ":"+secMilli);
// Call getTime() method to get the present date and time information.
System.out.println("At present Date and Time: " +cl.getTime());
}
}
Output: Current System Date: 19-1-2021 Current System Time: 3:56:35:343 At present Date and Time: Wed Jan 20 08:35:28 IST 2021
Explanation:
In this example program, we create an object of Calendar class that contains by default data and time information as shown by the local system.
From the calendar object, we get the date and time information separately using get() method and print them on the console.
Example 2: Let us write a Java program where we will get maximum and minimum numbers of days in a week, maximum and minimum number of weeks in a year. Look at the example code.
import java.util.Calendar;
public class CalendarDemo {
public static void main(String[] args)
{
// Create a calendar class object.
Calendar cl = Calendar.getInstance();
int maximum = cl.getMaximum(Calendar.DAY_OF_WEEK);
System.out.println("Maximum number of days in week: " + maximum);
maximum = cl.getMaximum(Calendar.WEEK_OF_YEAR);
System.out.println("Maximum number of weeks in year: " + maximum);
int minimum = cl.getMinimum(Calendar.DAY_OF_WEEK);
System.out.println("Minimum number of days in week: " + minimum);
minimum = cl.getMinimum(Calendar.WEEK_OF_YEAR);
System.out.println("Minimum number of weeks in year: " + minimum);
}
}
Output: Maximum number of days in week: 7 Maximum number of weeks in year: 53 Minimum number of days in week: 1 Minimum number of weeks in year: 1
Example 3: Let’s write a Java program and we will know the current date and time information, 20 days ago, 5 months later, and 5 years later date and time information from present now.
import java.util.Calendar;
public class CalendarDemo {
public static void main(String[] args)
{
// Create a calendar class object.
Calendar cl = Calendar.getInstance();
System.out.println("Current Date: " + cl.getTime());
cl.add(Calendar.DATE, -20);
System.out.println("20 Days ago, date and time information: " + cl.getTime());
cl.add(Calendar.MONTH, 5);
System.out.println("5 months later, date and time information: " + cl.getTime());
cl.add(Calendar.YEAR, 5);
System.out.println("5 years later, date and time information: " + cl.getTime());
}
}
Output: Current Date: Wed Jan 20 09:01:44 IST 2021 20 Days ago, date and time information: Thu Dec 31 09:01:44 IST 2020 5 months later, date and time information: Mon May 31 09:01:44 IST 2021 5 years later, date and time information: Sun May 31 09:01:44 IST 2026
How to Use Calendar in Java?
There are two ways to use the Calendar class in Java. They are as follows:
- Calendar class helps to know the system date and time information.
- It helps to store a date and time value so that it can be carried to some other applications.
In this tutorial, we have covered almost all the basic points related to Calendar class in Java with example programs. Hope that you will have understood this topic and practiced all examples based on the calendar methods. In the next, we will understand GregorianCalendar in Java.
Thanks for reading!!!