Java Calendar and GregorianCalendar Examples

Date is sufficient if we need only a current timestamp, but it doesn't have capability to operate on dates/times like add one year, add one hour, get one week before, etc. For these operation, we can use java.util.Calendar.

java.util.Calendar

The Calendar class provides support to access a set of calendar fields (YEAR, MONTH, DATE, HOUR, MINUTE, SECOND, MILLISECOND, etc) and manipulating them such as getting the date of the next week, back thirty minutes before, etc. Calendar also provides internationalization support.

The java.util.Calendar class is abstract, meaning you cannot instantiate it. Instead, you use the static method Calendar.getInstance() to instantiate an implementation sub-class.

CalendarInitExample.java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

public class CalendarInitExample {
    
    static void printCalendar(Calendar calendar, String name) {
        SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy");
        TimeZone timeZone = calendar.getTimeZone();
        sdf.setTimeZone(timeZone);

        System.out.printf("***** %s *****\n", name);
        System.out.printf("Time zone        : %s\n", timeZone.getID());
        System.out.printf("default time zone: %s\n", TimeZone.getDefault().getID());
        System.out.printf("UTC              : %s\n", sdf.format(calendar.getTime()));
        System.out.printf("Default          : %s\n", calendar.getTime());
        System.out.printf("First Day of Week: %s\n", calendar.getFirstDayOfWeek());
        System.out.println();
    }
    
    public static void main(String[] args) {       
        
        // create a calendar
        Calendar cal1 = Calendar.getInstance();
        printCalendar(cal1, "Calendar1");

        // create a calendar with locale
        Locale locale1 = Locale.FRANCE;
        Calendar cal2 = Calendar.getInstance(locale1);
        printCalendar(cal2, "Calendar2");

        // create a calendar with timezone
        TimeZone tz1 = TimeZone.getTimeZone("Europe/Copenhagen");
        Calendar cal3 = Calendar.getInstance(tz1);
        printCalendar(cal3, "Calendar3");

        // create a calendar with timezone and locale
        TimeZone tz2 = TimeZone.getTimeZone("Japan");
        Locale locale2 = Locale.FRANCE;
        Calendar cal4 = Calendar.getInstance(tz2, locale2);
        printCalendar(cal4, "Calendar4");
    }
}
                    

***** Calendar1 *****
Time zone        : Asia/Singapore
default time zone: Asia/Singapore
UTC              : Wed Jul 10 22:45:04 SGT 2019
Default          : Wed Jul 10 22:45:04 SGT 2019
First Day of Week: 1

***** Calendar2 *****
Time zone        : Asia/Singapore
default time zone: Asia/Singapore
UTC              : Wed Jul 10 22:45:04 SGT 2019
Default          : Wed Jul 10 22:45:04 SGT 2019
First Day of Week: 2

***** Calendar3 *****
Time zone        : Europe/Copenhagen
default time zone: Asia/Singapore
UTC              : Wed Jul 10 16:45:04 CEST 2019
Default          : Wed Jul 10 22:45:04 SGT 2019
First Day of Week: 1

***** Calendar4 *****
Time zone        : Japan
default time zone: Asia/Singapore
UTC              : Wed Jul 10 23:45:04 JST 2019
Default          : Wed Jul 10 22:45:04 SGT 2019
First Day of Week: 2

For function getFirstDayOfWeek() used in above example:

  • int getFirstDayOfWeek(): Gets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.

Field DAY_OF_WEEK (we will see about this later on) is a number indicating the day of the week, it start from 1 (SUNDAY) to 7 (SATURDAY). For Locale.FRANCE, getFirstDayOfWeek() will return 2, which is MONDAY.

Conversion between Calendar and Date

Like our example above, we can use getTime() and setTime() to convert between Calendar and Date.

  • Date getTime(): Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").
  • void setTime(Date date): Sets this Calendar's time with the given Date.
CalendarGetSetTimeExample.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CalendarGetSetTimeExample {
    
    public static void main(String[] args) {       
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss zzz");
        
        // create a calendar
        Calendar cal1 = Calendar.getInstance();
        // get Date from calendar using getTime
        Date date1 = cal1.getTime();
        System.out.println("date1: " + sdf.format(date1));
        
        try {
            Date date2 = sdf.parse("09-04-1980 02:40:10 SGT");
            System.out.println("date2: " + sdf.format(date2));
            Calendar cal2 = Calendar.getInstance();
            // set date to calendar 2
            cal2.setTime(date2);
            System.out.println("Calendar's date/time: " + sdf.format(cal2.getTime()));          
        } catch (ParseException ex) {
            System.out.println("ParseException occured: " + ex.getMessage());
        }        
    }
}
                    

date1: 09-07-2019 23:42:43 SGT
date2: 09-04-1980 02:40:10 SGT
Calendar's date/time: 09-04-1980 02:40:10 SGT

get() to Access Calendar's Fields

CalendarGetExample.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CalendarGetExample {
    
    public static void main(String[] args) {       
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss zzz");
        
        try {
            Date date = sdf.parse("18-04-1980 15:25:30 JST");
            System.out.println("date: " + sdf.format(date));
            Calendar cal = Calendar.getInstance();
            // set date to calendar
            cal.setTime(date);
            System.out.println("Calendar's date/time: " + sdf.format(cal.getTime()));
            System.out.println("Calendar's date  : " + cal.get(Calendar.DATE));
            // Month 0 is January
            System.out.println("Calendar's month : " + cal.get(Calendar.MONTH));
            System.out.println("Calendar's year  : " + cal.get(Calendar.YEAR));
            System.out.println("Calendar's hour  : " + cal.get(Calendar.HOUR));
            System.out.println("Calendar's minute: " + cal.get(Calendar.MINUTE));
            System.out.println("Calendar's second: " + cal.get(Calendar.SECOND));            
        } catch (ParseException ex) {
            System.out.println("ParseException occured: " + ex.getMessage());
        }        
    }
}
                    

date: 18-04-1980 15:25:30 JST
Calendar's date/time: 18-04-1980 15:25:30 JST
Calendar's date  : 18
Calendar's month : 3
Calendar's year  : 1980
Calendar's hour  : 1
Calendar's minute: 55
Calendar's second: 30

Be aware that MONTH field of the Calendar class run from 0 to 11, where 0 is January and 11 is December. This also applicable to set(...) methods below.

set() to Modify Calendar's Fields

CalendarSetExample.java
import java.util.Calendar;

public class CalendarSetExample {
    
    public static void main(String[] args) {       
        Calendar cal = Calendar.getInstance();
        
        // Set
        cal.set(1980, 3, 18);
        System.out.println("Calendar's date/time: " + cal.getTime());
        System.out.println("Calendar's date  : " + cal.get(Calendar.DAY_OF_MONTH));
        System.out.println("Calendar's month : " + cal.get(Calendar.MONTH));
        System.out.println("Calendar's year  : " + cal.get(Calendar.YEAR));
        System.out.println();
        
        cal.set(2002, 2, 22, 14, 20);
        System.out.println("Calendar's date/time: " + cal.getTime());
        System.out.println("Calendar's hour  : " + cal.get(Calendar.HOUR_OF_DAY));
        System.out.println("Calendar's minute: " + cal.get(Calendar.MINUTE));
        System.out.println();
        
        cal.set(1981, 6, 12, 20, 30, 40);
        System.out.println("Calendar's date/time: " + cal.getTime());
        System.out.println("Calendar's hour  : " + cal.get(Calendar.HOUR_OF_DAY));
        System.out.println("Calendar's minute: " + cal.get(Calendar.MINUTE));
        System.out.println("Calendar's second: " + cal.get(Calendar.SECOND));
        System.out.println();
        
        cal.set(Calendar.YEAR, 1981);
        cal.set(Calendar.MONTH, 3);
        cal.set(Calendar.DATE, 11);
        System.out.println("Calendar's date/time: " + cal.getTime());
        System.out.println("Calendar's date  : " + cal.get(Calendar.DATE));
        System.out.println("Calendar's month : " + cal.get(Calendar.MONTH));
        System.out.println("Calendar's year  : " + cal.get(Calendar.YEAR));
    }
}
                    

Calendar's date/time: Fri Apr 18 01:40:34 SGT 1980
Calendar's date  : 18
Calendar's month : 3
Calendar's year  : 1980

Calendar's date/time: Fri Mar 22 14:20:34 SGT 2002
Calendar's hour  : 14
Calendar's minute: 20

Calendar's date/time: Sun Jul 12 20:30:40 SGT 1981
Calendar's hour  : 20
Calendar's minute: 30
Calendar's second: 40

Calendar's date/time: Sat Apr 11 20:30:40 SGT 1981
Calendar's date  : 11
Calendar's month : 3
Calendar's year  : 1981

Adding and Subtracting Calendar's Fields

  • void add(int field, int amount): Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.

The add() method is used to add or subtract years, months, days, hours, minutes, seconds, etc from a given Calendar. To subtract from the fields we can set amount with negative value.

CalendarAddExample.java
import java.util.Calendar;

public class CalendarAddExample {
    
    public static void main(String[] args) {       
        Calendar cal = Calendar.getInstance();
        
        cal.set(1979, 11, 9, 10, 20, 30);
        System.out.println("Calendar's date/time: " + cal.getTime());
        System.out.println("Calendar's date  : " + cal.get(Calendar.DATE));
        System.out.println("Calendar's month : " + cal.get(Calendar.MONTH));
        System.out.println("Calendar's year  : " + cal.get(Calendar.YEAR));
        System.out.println();
        
        cal.add(Calendar.MONTH, 4);
        System.out.println("Calendar's date/time: " + cal.getTime());
        System.out.println("Calendar's date  : " + cal.get(Calendar.DATE));
        System.out.println("Calendar's month : " + cal.get(Calendar.MONTH));
        System.out.println("Calendar's year  : " + cal.get(Calendar.YEAR));
        System.out.println();
        
        cal.add(Calendar.YEAR, 39);
        cal.add(Calendar.MONTH, -6);
        System.out.println("Calendar's date/time: " + cal.getTime());
        System.out.println("Calendar's date  : " + cal.get(Calendar.DATE));
        System.out.println("Calendar's month : " + cal.get(Calendar.MONTH));
        System.out.println("Calendar's year  : " + cal.get(Calendar.YEAR));
    }
}
                    

Calendar's date/time: Sun Dec 09 10:20:30 SGT 1979
Calendar's date  : 9
Calendar's month : 11
Calendar's year  : 1979

Calendar's date/time: Wed Apr 09 10:20:30 SGT 1980
Calendar's date  : 9
Calendar's month : 3
Calendar's year  : 1980

Calendar's date/time: Tue Oct 09 10:20:30 SGT 2018
Calendar's date  : 9
Calendar's month : 9
Calendar's year  : 2018

java.util.GregorianCalendar

GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar system used by most of the world. Calendar.getInstance() returns an implementation class java.util.GregorianCalendar except JapaneseImperialCalendar for Japanese ("ja_JP_JP_#u-ca-japanese") and BuddhistCalendar for Thai ("th_TH").

GregorianCalendarDefaultedExample.java
import java.util.Calendar;
import java.util.Locale;

public class GregorianCalendarDefaultedExample {
    
    public static void main(String[] args) {               
        Locale locale1 = Locale.getDefault();
        Calendar cal1 = Calendar.getInstance();
        System.out.println("Locale  : " + locale1);
        System.out.println("Calendar: " + cal1.getClass().getName());
        System.out.println("Year    : " + cal1.get(Calendar.YEAR));
        System.out.println("Month   : " + cal1.get(Calendar.MONTH));
        System.out.println("Date    : " + cal1.get(Calendar.DATE));
        System.out.println();
        
        Locale locale2 = new Locale("ja", "JP", "JP");
        Calendar cal2 = Calendar.getInstance(locale2);
        System.out.println("Locale  : " + locale2);
        System.out.println("Calendar: " + cal2.getClass().getName());
        System.out.println("Year    : " + cal2.get(Calendar.YEAR));
        System.out.println("Month   : " + cal2.get(Calendar.MONTH));
        System.out.println("Date    : " + cal2.get(Calendar.DATE));
        System.out.println();
        
        Locale locale3 = new Locale("th", "TH");
        Calendar cal3 = Calendar.getInstance(locale3);
        System.out.println("Locale  : " + locale3);
        System.out.println("Calendar: " + cal3.getClass().getName());
        System.out.println("Year    : " + cal3.get(Calendar.YEAR));
        System.out.println("Month   : " + cal3.get(Calendar.MONTH));
        System.out.println("Date    : " + cal3.get(Calendar.DATE));
    }
}
                    

Locale  : en_SG
Calendar: java.util.GregorianCalendar
Year    : 2019
Month   : 6
Date    : 10

Locale  : ja_JP_JP_#u-ca-japanese
Calendar: java.util.JapaneseImperialCalendar
Year    : 31
Month   : 6
Date    : 10

Locale  : th_TH
Calendar: sun.util.BuddhistCalendar
Year    : 2562
Year    : 2562
Month   : 6
Date    : 10

GregorianCalendar has the following constructors:

GregorianCalendarInitExample.java
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

public class GregorianCalendarInitExample {
    
    static void printCalendar(GregorianCalendar calendar, String name) {
        SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy");
        TimeZone timeZone = calendar.getTimeZone();
        sdf.setTimeZone(timeZone);

        System.out.printf("***** %s *****\n", name);
        System.out.printf("Time zone        : %s\n", timeZone.getID());
        System.out.printf("default time zone: %s\n", TimeZone.getDefault().getID());
        System.out.printf("UTC              : %s\n", sdf.format(calendar.getTime()));
        System.out.printf("Default          : %s\n", calendar.getTime());
        System.out.printf("First Day of Week: %s\n", calendar.getFirstDayOfWeek());
        System.out.println();
    }
    
    public static void main(String[] args) {       
        
        // create a GregorianCalendar
        GregorianCalendar cal1 = new GregorianCalendar();
        printCalendar(cal1, "Calendar1");

        GregorianCalendar cal2 = new GregorianCalendar(1980, 3, 9);
        printCalendar(cal2, "Calendar2");
        
        GregorianCalendar cal3 = new GregorianCalendar(1980, 3, 9, 10, 20);
        printCalendar(cal3, "Calendar3");
        
        GregorianCalendar cal4 = new GregorianCalendar(1980, 3, 9, 10, 20, 30);
        printCalendar(cal4, "Calendar4");
        
        // create a GregorianCalendar with locale
        Locale locale1 = Locale.FRANCE;
        GregorianCalendar cal5 = new GregorianCalendar(locale1);
        printCalendar(cal5, "Calendar5");

        // create a GregorianCalendar with timezone
        TimeZone tz1 = TimeZone.getTimeZone("Europe/Copenhagen");
        GregorianCalendar cal6 = new GregorianCalendar(tz1);
        printCalendar(cal6, "Calendar6");

        // create a GregorianCalendar with different timezone and locale
        TimeZone tz2 = TimeZone.getTimeZone("Japan");
        Locale locale2 = Locale.FRANCE;
        GregorianCalendar cal7 = new GregorianCalendar(tz2, locale2);
        printCalendar(cal7, "Calendar7");
    }
}
                    

***** Calendar1 *****
Time zone        : Asia/Singapore
default time zone: Asia/Singapore
UTC              : Wed Jul 10 22:46:26 SGT 2019
Default          : Wed Jul 10 22:46:26 SGT 2019
First Day of Week: 1

***** Calendar2 *****
Time zone        : Asia/Singapore
default time zone: Asia/Singapore
UTC              : Wed Apr 09 00:00:00 SGT 1980
Default          : Wed Apr 09 00:00:00 SGT 1980
First Day of Week: 1

***** Calendar3 *****
Time zone        : Asia/Singapore
default time zone: Asia/Singapore
UTC              : Wed Apr 09 10:20:00 SGT 1980
Default          : Wed Apr 09 10:20:00 SGT 1980
First Day of Week: 1

***** Calendar4 *****
Time zone        : Asia/Singapore
default time zone: Asia/Singapore
UTC              : Wed Apr 09 10:20:30 SGT 1980
Default          : Wed Apr 09 10:20:30 SGT 1980
First Day of Week: 1

***** Calendar5 *****
Time zone        : Asia/Singapore
default time zone: Asia/Singapore
UTC              : Wed Jul 10 22:46:26 SGT 2019
Default          : Wed Jul 10 22:46:26 SGT 2019
First Day of Week: 2

***** Calendar6 *****
Time zone        : Europe/Copenhagen
default time zone: Asia/Singapore
UTC              : Wed Jul 10 16:46:26 CEST 2019
Default          : Wed Jul 10 22:46:26 SGT 2019
First Day of Week: 1

***** Calendar7 *****
Time zone        : Japan
default time zone: Asia/Singapore
UTC              : Wed Jul 10 23:46:26 JST 2019
Default          : Wed Jul 10 22:46:26 SGT 2019
First Day of Week: 2

Conclusion

GregorianCalendar is a concrete implementation of the abstract class java.util.Calendar.

In most locales, when you write Calendar.getInstance(), it will create a GregorianCalendar object. But there are a few exceptions as a JapaneseImperialCalendar for Japan Locale or a BuddhistCalendar for Thai Locale (example above). You can explicitly write new GregorianCalendar() to get an instance of GregorianCalendar. Although it's advisable to let the JVM choose the right kind of Calendar based on the locale.

You can use getTime() and setTime() to convert between Calendar and Date.