Java Calendar Class

The Calendar class is an abstract class in Java for handling dates and times. It is located in thejava.utilpackage. This class provides a series of methods to operate on date and time fields (such as year, month, day, hour, minute, etc.), and can perform date calculations and comparisons.

Why do we need the Calendar class?

In Java, although the Date class can also represent dates and times, it has the following limitations:

  1. Most methods are deprecated
  2. Does not support internationalization
  3. Limited date calculation functionality

The Calendar class solves these problems and provides more powerful and flexible date-time manipulation capabilities.


Basic usage of the Calendar class

Getting a Calendar instance

Since Calendar is an abstract class, we cannot instantiate it directly. The standard way to obtain a Calendar instance is:

Example

Calendar calendar = Calendar.getInstance();

This method returns a Calendar instance (usually GregorianCalendar) based on the default time zone and locale.

Setting date and time

We can use theset()method to set the various fields of a Calendar object:

Example

// Set year, month, and day
calendar.set(2023, Calendar.NOVEMBER, 15);

// Set year, month, day, hour, minute, and second
calendar.set(2023, Calendar.NOVEMBER, 15, 14, 30, 0);

Note: Months are 0-based, where 0 represents January and 11 represents December. To avoid confusion, it is recommended to use the constants defined in the Calendar class (e.g., Calendar.JANUARY, Calendar.FEBRUARY, etc.).

Getting date and time information

Use theget()method to get the various fields of a Calendar object:

Example

int year = calendar.get(Calendar.YEAR);       // Get the year
int month = calendar.get(Calendar.MONTH);     // Get the month (0-11)
int day = calendar.get(Calendar.DAY_OF_MONTH);// Get the day
int hour = calendar.get(Calendar.HOUR_OF_DAY);// Get the hour (24-hour format)
int minute = calendar.get(Calendar.MINUTE);   // Get the minute
int second = calendar.get(Calendar.SECOND);   // Get the second

Common methods of the Calendar class

Date calculation

The Calendar class provides convenient date calculation methods:

Example

// Add 10 days to the current date
calendar.add(Calendar.DAY_OF_MONTH, 10);

// Subtract 3 months from the current month
calendar.add(Calendar.MONTH, -3);

Date comparison

We can use thecompareTo()method to compare two Calendar objects:

Example

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.DAY_OF_MONTH, 1);

int result = cal1.compareTo(cal2);
// result < 0 indicates cal1 is earlier than cal2
// result == 0 indicates cal1 is equal to cal2
// result > 0 indicates cal1 is later than cal2

Getting a timestamp

You can use thegetTimeInMillis()method to get the timestamp (milliseconds) represented by a Calendar object:

Example

long timestamp = calendar.getTimeInMillis();

You can also use thegetTime()method to convert it to a Date object:

Example

Date date = calendar.getTime();

Advanced usage of the Calendar class

Setting time zone

We can set a specific time zone for a Calendar object:

Example

TimeZone timeZone = TimeZone.getTimeZone("America/New_York");
calendar.setTimeZone(timeZone);

Calendar field operations

The Calendar class provides theroll()method, which can roll a field without affecting other fields:

Example

// Add 1 to the month, but do not change the year
calendar.roll(Calendar.MONTH, true);  // Or calendar.roll(Calendar.MONTH, 1);

Getting the first day of the week

Different regions define the first day of the week differently (some use Sunday, some use Monday):

Example

int firstDayOfWeek = calendar.getFirstDayOfWeek();

Comprehensive example

Example

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;

public class CalendarDemo {
    public static void main(String[] args) {
        // 1. Get a Calendar instance (uses current date and time by default)
        Calendar calendar = Calendar.getInstance();
       
        // 2. Get the values of various fields
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // The month is 0-based, so add 1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY); // 24-hour format
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
       
        System.out.printf("Current time: %d year %d month %d day %d:%d:%d%n",
                        year, month, day, hour, minute, second);
       
        // 3. Set a specific date and time
        calendar.set(2023, Calendar.MAY, 15, 10, 30, 0); // May 15, 2023 10:30:00
       
        // 4. Use SimpleDateFormat for formatted output
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Time after setting: " + sdf.format(calendar.getTime()));
       
        // 5. Date arithmetic
        calendar.add(Calendar.DAY_OF_MONTH, 5); // Add 5 days
        calendar.add(Calendar.HOUR, -3); // Subtract 3 hours
       
        System.out.println("Time after calculation: " + sdf.format(calendar.getTime()));
       
        // 6. Compare dates
        Calendar anotherCalendar = new GregorianCalendar(2023, Calendar.JUNE, 1);
        System.out.println("Comparison result: " +
            (calendar.before(anotherCalendar) ? "before" : "after"));
       
        // 7. Get the day of the week (Sunday=1, Saturday=7)
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        System.out.println("Day of week" + getChineseWeekday(dayOfWeek));
    }
   
    private static String getChineseWeekday(int dayOfWeek) {
        String[] weekdays = {"", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
        return weekdays[dayOfWeek];
    }
}

Output result:

当前时间: 2023年5月15日 14:25:36
设置后的时间: 2023-05-15 10:30:00
运算后的时间: 2023-05-20 07:30:00
比较结果: 之前
星期二

Notes on the Calendar class

  1. Months are 0-based: In the Calendar class, months are 0-based (0=January, 11=December), which can easily lead to errors.

  2. Mutability: Calendar objects are mutable; modifying one Calendar object affects all places that reference it.

  3. Thread safety: The Calendar class is not thread-safe, and extra synchronization is needed in multi-threaded environments.

  4. Performance: Frequently creating Calendar instances affects performance; consider reusing instances.

  5. Time zone issues: The system time zone is used by default, and special attention is needed for cross-time-zone applications.


Alternative in Java 8

Starting from Java 8, a new date-time API (thejava.timepackage) was introduced, providing a more modern and easier-to-use way to handle dates and times. If you are using Java 8 or later, it is recommended to prefer the new API:

Example

// New API to replace Calendar
LocalDate date = LocalDate.now();
LocalDateTime dateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.now();

The new API solves many problems of the Calendar class, including better thread safety, a more intuitive API design, and more powerful functionality.


Common methods of the Java Calendar class

The following are common methods of the java.util.Calendar class:

Basic methods

Method Description Example
static Calendar getInstance() Gets a Calendar instance with the default time zone and locale Calendar cal = Calendar.getInstance()
static Calendar getInstance(TimeZone zone) Gets a Calendar instance with the specified time zone Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"))
static Calendar getInstance(Locale locale) Gets a Calendar instance with the specified locale Calendar cal = Calendar.getInstance(Locale.CHINA)
static Calendar getInstance(TimeZone zone, Locale locale) Gets a Calendar instance with the specified time zone and locale Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"), Locale.CHINA)

Field constants (common)

Field Description Value range
Calendar.YEAR Year field -
Calendar.MONTH Month field 0-11 (0 means January)
Calendar.DATEorCalendar.DAY_OF_MONTH Number of days in the month 1-31
Calendar.DAY_OF_WEEK Day of the week 1-7 (1 means Sunday)
Calendar.HOUR Hour in 12-hour format 0-11
Calendar.HOUR_OF_DAY Hour in 24-hour format 0-23
Calendar.MINUTE Minutes 0-59
Calendar.SECOND second 0-59
Calendar.MILLISECOND Milliseconds 0-999
Calendar.AM_PM AM or PM 0 (AM) or 1 (PM)

Date-time operation methods

Method Description Example
int get(int field) Get the value of the specified field int year = cal.get(Calendar.YEAR)
void set(int field, int value) Set the value of the specified field cal.set(Calendar.MONTH, 5)(set to June)
void set(int year, int month, int date) Set year, month, day cal.set(2023, 5, 15)(June 15, 2023)
void set(int year, int month, int date, int hourOfDay, int minute) Set year, month, day, hour, minute cal.set(2023, 5, 15, 14, 30)
void set(int year, int month, int date, int hourOfDay, int minute, int second) Set year, month, day, hour, minute, second cal.set(2023, 5, 15, 14, 30, 45)
void add(int field, int amount) Add or subtract the specified amount of time cal.add(Calendar.DATE, 5)(add 5 days)
void roll(int field, int amount) Add or subtract an amount of time without changing larger fields cal.roll(Calendar.DATE, 5)(only changes the day field)

Time comparison methods

Method Description Example
boolean after(Object when) Determine whether this Calendar is after the specified time cal1.after(cal2)
boolean before(Object when) Determine whether this Calendar is before the specified time cal1.before(cal2)
int compareTo(Calendar anotherCalendar) Compare the chronological order of two Calendar objects cal1.compareTo(cal2)

Other useful methods

Method Description Example
long getTimeInMillis() Return the time value of this Calendar (milliseconds) long millis = cal.getTimeInMillis()
void setTimeInMillis(long millis) Set the Calendar with the given millisecond time value cal.setTimeInMillis(1626345600000L)
Date getTime() Return a Date object representing this Calendar's time value Date date = cal.getTime()
void setTime(Date date) Set the Calendar's time using the given Date cal.setTime(new Date())
void clear() Clear all field values cal.clear()
void clear(int field) Clear the value of the specified field cal.clear(Calendar.HOUR)
boolean isSet(int field) Determine whether the specified field has been set if(cal.isSet(Calendar.YEAR))
Other extensions