Calendar class in Java is an abstract class that provides methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and implements the Comparable, Serializable, Cloneable interfaces.
As it is an Abstract class, so we cannot use a constructor to create an instance. Instead, we will have to use the static method Calendar.getInstance() to instantiate and implement a sub-class.
- Calendar.getInstance(): return a Calendar instance based on the current time in the default time zone with the default locale.
- Calendar.getInstance(TimeZone zone)
- Calendar.getInstance(Locale aLocale)
- Calendar.getInstance(TimeZone zone, Locale aLocale)
Java program to demonstrate getInstance() method:
The Current Date is:Tue Aug 28 11:10:40 UTC 2018
Important Methods and their usage
|abstract void add(int field, int amount)||It is used to add or subtract the specified amount of time to the given calendar field, based on the calendar’s rules.|
|int get(int field)||It is used to return the value of the given calendar field.|
|abstract int getMaximum(int field)||It is used to return the maximum value for the given calendar field of this Calendar instance.|
|abstract int getMinimum(int field)||It is used to return the minimum value for the given calendar field of this Calendar instance.|
|Date getTime()||It is used to return a Date object representing this Calendar’s time value.</td|
Below programs illustrate the above methods:
Program 1: Java program to demonstrate get() method.
Current Calendar's Year: 2018 Current Calendar's Day: 28 Current MINUTE: 10 Current SECOND: 45
Program 2: Java program to demonstrate getMaximum() method.
Maximum number of days in a week: 7 Maximum number of weeks in a year: 53
Program 3: Java program to demonstrate the getMinimum() method.
Minimum number of days in week: 1 Minimum number of weeks in year: 1
Program 4: Java program to demonstrate add() method.
15 days ago: Mon Aug 13 11:10:57 UTC 2018 4 months later: Thu Dec 13 11:10:57 UTC 2018 2 years later: Sun Dec 13 11:10:57 UTC 2020
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.