Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Calendar Class

Java Calendar Class

The Calendar class is an abstract class in Java for handling dates and times; it is located in java.util package. This class provides a series of methods to manipulate 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. No internationalization support
  3. Limited date calculation functionality

The Calendar class solves these problems, providing more powerful and flexible date-time manipulation functions.


Basic Usage of the Calendar Class

Get a Calendar instance

Since Calendar is an abstract class, we cannot instantiate it directly. The standard way to get 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.

Set Date and Time

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

Example

// Set year, month, day

calendar.

set

(

2023

,

Calendar

.

NOVEMBER

,

15

)

;

// Set year, month, day, hour, minute, second

calendar.

set

(

2023

,

Calendar

.

NOVEMBER

,

15

,

14

,

30

,

0

)

;

Note: The month starts from 0, where 0 means January and 11 means December. To avoid confusion, it is recommended to use the constants defined in the Calendar class (such as Calendar.JANUARY, Calendar.FEBRUARY, etc.).

Get Date and Time Information

Use get() method can get the various fields in the Calendar object:

Example

int

year

=

calendar.

get

(

Calendar

.

YEAR

)

;

     

// Get year

int

month

=

calendar.

get

(

Calendar

.

MONTH

)

;

   

// Get month (0-11)

int

day

=

calendar.

get

(

Calendar

.

DAY_OF_MONTH

)

;

// Get day

int

hour

=

calendar.

get

(

Calendar

.

HOUR_OF_DAY

)

;

// Get hour (24-hour format)

int

minute

=

calendar.

get

(

Calendar

.

MINUTE

)

;

 

// Get minute

int

second

=

calendar.

get

(

Calendar

.

SECOND

)

;

 

// Get 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 the compareTo() method compares 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 means cal1 is earlier than cal2

// result == 0 means cal1 equals cal2

// result > 0 means cal1 is later than cal2

Get Timestamp

You can use the getTimeInMillis() method gets the timestamp (milliseconds) represented by the Calendar object:

Example

long

timestamp

=

calendar.

getTimeInMillis

(

)

;

You can also use getTime() method converts it to a Date object:

Example

Date

date

=

calendar.

getTime

(

)

;


Advanced Usage of the Calendar Class

Set Time Zone

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

Example

TimeZone

timeZone

=

TimeZone

.

getTimeZone

(

"America/New_York"

)

;

calendar.

setTimeZone

(

timeZone

)

;

Calendar Field Operations

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

Example

// Increment the month by 1, but do not change the year

calendar.

roll

(

Calendar

.

MONTH

,

true

)

;

 

// or calendar.roll(Calendar.MONTH, 1);

Get the First Day of the Week

Different regions define the first day of the week differently (some are Sunday, some are 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 each field

       

int

year

=

calendar.

get

(

Calendar

.

YEAR

)

;

       

int

month

=

calendar.

get

(

Calendar

.

MONTH

)

1

;

// Month starts from 0, need to 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-%d-%d %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

)

;

// 2023-05-15 10:30:00

       

       

// 4. Use SimpleDateFormat to format the output

       

SimpleDateFormat

sdf

=

new

SimpleDateFormat

(

"yyyy-MM-dd HH:mm:ss"

)

;

       

System

.

out

.

println

(

Time after setting:

sdf.

format

(

calendar.

getTime

(

)

)

)

;

       

       

// 5. Date operations

        calendar.

add

(

Calendar

.

DAY_OF_MONTH

,

5

)

;

// Add 5 days

        calendar.

add

(

Calendar

.

HOUR

,

3

)

;

// Subtract 3 hours

       

       

System

.

out

.

println

(

Time after operation:

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

(

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. Month starts from 0: In the Calendar class, the month starts from 0 (0=January, 11=December), which can easily cause 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; additional synchronization is needed in multi-threaded environments.

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

  5. Time Zone Issues: Uses the system time zone by default; cross-time-zone applications need special attention.


Alternatives in Java 8

Starting from Java 8, a new date-time API (java.time package) was introduced, providing a more modern and easier-to-use way of handling dates and times. If you use Java 8 or higher, it is recommended to prioritize the new API:

Example

// New API replacing 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, more intuitive API design, and more powerful functionality.


Common Methods of the Java Calendar Class

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

Basic Methods

Method Description Example
static Calendar getInstance() Get a Calendar instance for the default time zone and locale Calendar cal = Calendar.getInstance()
static Calendar getInstance(TimeZone zone) Get a Calendar instance for the specified time zone Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"))
static Calendar getInstance(Locale locale) Get a Calendar instance for the specified locale Calendar cal = Calendar.getInstance(Locale.CHINA)
static Calendar getInstance(TimeZone zone, Locale locale) Get a Calendar instance for 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.DATE or Calendar.DAY_OF_MONTH Day of month 1-31
Calendar.DAY_OF_WEEK Day of week 1-7 (1 means Sunday)
Calendar.HOUR Hour (12-hour) 0-11
Calendar.HOUR_OF_DAY Hour (24-hour) 0-23
Calendar.MINUTE Minute 0-59
Calendar.SECOND Second 0-59
Calendar.MILLISECOND Millisecond 0-999
Calendar.AM_PM AM or PM 0 (AM) or 1 (PM)

Date and Time Operation Methods

Method Description Example
int get(int field) Get the value of a specified field int year = cal.get(Calendar.YEAR)
void set(int field, int value) Set the value of a 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) (2023-06-15)
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 a specified amount of time cal.add(Calendar.DATE, 5) (add 5 days)
void roll(int field, int amount) Add or subtract a time amount 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 time order of two Calendar objects cal1.compareTo(cal2)

Other Utility 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 the 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 a specified field cal.clear(Calendar.HOUR)
boolean isSet(int field) Determine whether a specified field has been set if(cal.isSet(Calendar.YEAR))