Java Calendar Examples

A Tutorial covering the basics of Java Calendar and Date Manipulation

“Let us tenderly and kindly cherish therefore, the means of knowledge. Let us dare to read, think, speak, and write .”
― John Adams

1. Introduction

Java provides a Calendar class for performing data manipulation. A closely related class is the Date class, used to represent a specific instant in time starting from epoch (January 1, 1970 00:00:00.000 GMT). Let use learn how we can use these two classes for date and time manipulation.

2. Create a Calendar and a Date

The method getTime() returns a Date instance which is the time represented by the Calendar. The getInstance() static method returns the current date and time in the current timezone.

Calendar cal = Calendar.getInstance();
System.out.println("date => " + cal.getTime());
# prints
date => Thu Aug 10 21:56:03 EST 2017

3. Changing the Time Zone

Once you have a Calendar instance, how do you change its time zone? Using the setTimeZone() method as follows.

Calendar cal = Calendar.getInstance();
TimeZone tz = TimeZone.getTimeZone("GMT");
System.out.println("date => " + cal.getTime());
# prints
date => Thu Aug 10 22:08:29 EST 2017

Note that the time zone is not a property of the Date instance. The Date instance just represents an instant with millisecond precision.

You can format a date using the SimpleDateFormat class. For example, to format the date in the same form as above, use the following code:

SimpleDateFormat fmt = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy");
System.out.println("fmt  => " + fmt.format(cal.getTime()));
# prints
fmt  => Thu Aug 10 22:31:09 EST 2017

Note that the time zone used by the SimpleDateFormat instance is the platform default. To format the date with the correct time zone (as set in the Calendar), you need to set the DateFormat‘s calendar.

fmt.setCalendar(cal);
System.out.println("fmt  => " + fmt.format(cal.getTime()));
# prints
fmt  => Fri Aug 11 03:31:09 GMT 2017

4. Date Math – Addition and Subtraction

The Calendar class provides an add() method which allows you to add and subtract specific fields. For instance to add 4 days to a Calendar instance:

Calendar cal = Calendar.getInstance();
System.out.println(" b4 => " + toString(cal));
cal.add(Calendar.DAY_OF_MONTH, 4);
System.out.println("add => " + toString(cal));
# prints
 b4 => Thu Aug 10 23:46:57 EST 2017
add => Mon Aug 14 23:46:57 EST 2017

To subtract, specify a negative number for the second argument of the add() method.

Calendar cal = Calendar.getInstance();
System.out.println(" b4 => " + toString(cal));
cal.add(Calendar.MINUTE, -87);
System.out.println("sub => " + toString(cal));
# prints
 b4 => Fri Aug 11 01:40:45 EST 2017
sub => Fri Aug 11 00:13:45 EST 2017

The convenience method toString() above is defined as follows. The SimpleDateFormat is initialized with the Calendar instance to get the correct time zone as explained above.

static private SimpleDateFormat format =
    new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy");

static private String toString(Calendar cal)
{
    format.setCalendar(cal);
    return format.format(cal.getTime());
}

The fields which can be used in set(), add() and roll() are:

  • Calendar.DATE and Calendar.DAY_OF_MONTH: Day of the month.
  • Calendar.DAY_OF_WEEK: Day of the week.
  • Calendar.DAY_OF_WEEK_IN_MONTH: Day of the week within the month.
  • Calendar.DAY_OF_YEAR: Day of the year.
  • Calendar.MONTH: Month value.
  • Calendar.YEAR: Year value.
  • Calendar.WEEK_OF_MONTH: Week number within the month.
  • Calendar.WEEK_OF_YEAR: Week number within the year.
  • Calendar.HOUR_OF_DAY: Hour of the day.
  • Calendar.HOUR: Hour of the morning or afternoon.
  • Calendar.MINUTE: Minute within the hour.
  • Calendar.SECOND: Second within the minute.
  • Calendar.MILLISECOND: Millisecond within the second.
  • Calendar.ZONE_OFFSET: Offset from GMT in milliseconds.
  • Calendar.DST_OFFSET: Daylight Saving Offset in milliseconds.
  • Calendar.AM_PM: Whether the HOUR is before or after noon.
  • Calendar.ERA: The Era (AD or BC in the Julian calendar).

The method roll() increments (or decrements when given a negative value) the specified field.

Calendar cal = Calendar.getInstance();
System.out.println("  b4 => " + toString(cal));
cal.roll(Calendar.HOUR_OF_DAY, 4);
System.out.println("roll => " + toString(cal));
# prints
  b4 => Fri Aug 11 01:24:38 EST 2017
roll => Fri Aug 11 05:24:38 EST 2017

5. Setting the Fields

The method set() can be used to set the fields directly. Appropriate updates are made to all the other fields when a retrieval method such as getTime() is invoked.

Calendar cal = Calendar.getInstance();
System.out.println(" b4 => " + toString(cal));
cal.set(Calendar.DAY_OF_MONTH, 45);
System.out.println("set => " + toString(cal));
# prints
 b4 => Fri Aug 11 01:32:22 EST 2017
set => Thu Sep 14 01:32:22 EST 2017

Set the complete date, including the year, month and day of the month in a single call. The following example illustrates that the other fields are adjusted so that the date is a valid date.

Calendar cal = Calendar.getInstance();
System.out.println(" b4 => " + toString(cal));
cal.set(2017, 1, 31);
System.out.println("set => " + toString(cal));
# prints
 b4 => Fri Aug 11 01:36:41 EST 2017
set => Fri Mar 03 01:36:41 EST 2017

The month being set above is February since the month number starts from 0 for January.

Review

In this beginner tutorial, we saw how to use the Calendar class to perform date math. From setting the time zone to adding values to various fields and setting the fields directly.

Leave a Reply

Your email address will not be published. Required fields are marked *