Java Calendar by Examples

Tags: Calendar Java Calendar

In this Java core tutorial we learn how to use the java.util.Calendar class in Java via different example codes.

Table of contents

  1. Create Calendar object using Calendar.Builder class
  2. Gets Calendar instance with default time zone and locale
  3. Get Calendar instance with given time zone or locale
  4. Get Array of Available Locales
  5. Convert Calendar to Date
  6. Convert Date to Calendar
  7. Convert Calendar to Milliseconds
  8. Convert Milliseconds to Calendar
  9. Convert Calendar to Instant
  10. Get Calendar field values
  11. Set value for Calendar fields
  12. Set day month year hour minute seconds of Calendar
  13. Clear field values of Calendar
  14. Get Display Name of Calendar Fields
  15. Get All Available Calendar Types
  16. Compare two Calendar objects for Equality
  17. Compare two Calendar objects for Ordering
  18. Check if a Calendar before another Calendar
  19. Check if a Calendar after another Calendar
  20. Add or Subtract field values of Calendar
  21. Roll up or down a single field unit of Calendar
  22. How to clone Calendar object

Create Calendar object using Calendar.Builder class

In Java we can use the Calendar.Builder class to build a new instance of Calendar as below example Java code.

CalendarExample1.java

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

public class CalendarExample1 {
    public static void main(String... args) {
        Calendar calendar = new Calendar.Builder()
                .set(Calendar.DAY_OF_MONTH, 11)
                .set(Calendar.MONTH, Calendar.JULY)
                .set(Calendar.YEAR, 2022)
                .set(Calendar.HOUR, 8)
                .set(Calendar.MINUTE, 30)
                .set(Calendar.SECOND, 00)
                .build();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }
}
The output as below.
2022/07/11 08:30:00

Gets Calendar instance with default time zone and locale

Using the Calendar.getInstance() static method we can instantiate a new Calendar object with default time zone and locale.

CalendarExample2.java

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

public class CalendarExample2 {
    public static void main(String... args) {
        Calendar calendar = Calendar.getInstance();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }
}
The output as below.
2022/04/15 22:36:50

Get Calendar instance with given time zone or locale

With Calendar.getInstance() method we can also instantiate Calendar object with given time zone or locale.

CalendarExample3.java

import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

public class CalendarExample3 {
    public static void main(String... args) {
        TimeZone timeZone = TimeZone.getTimeZone("America/New_York");

        Calendar calendar1 = Calendar.getInstance(timeZone);
        Calendar calendar2 = Calendar.getInstance(Locale.CANADA);
        Calendar calendar3 = Calendar.getInstance(timeZone, Locale.CANADA);

        System.out.println(calendar1);
        System.out.println(calendar2);
        System.out.println(calendar3);
    }
}
The output as below.
java.util.GregorianCalendar[time=1650037304098,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=3,WEEK_OF_YEAR=16,WEEK_OF_MONTH=3,DAY_OF_MONTH=15,DAY_OF_YEAR=105,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=41,SECOND=44,MILLISECOND=98,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
java.util.GregorianCalendar[time=1650037304107,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Bangkok",offset=25200000,dstSavings=0,useDaylight=false,transitions=3,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=3,WEEK_OF_YEAR=16,WEEK_OF_MONTH=3,DAY_OF_MONTH=15,DAY_OF_YEAR=105,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=41,SECOND=44,MILLISECOND=107,ZONE_OFFSET=25200000,DST_OFFSET=0]
java.util.GregorianCalendar[time=1650037304107,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=3,WEEK_OF_YEAR=16,WEEK_OF_MONTH=3,DAY_OF_MONTH=15,DAY_OF_YEAR=105,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=41,SECOND=44,MILLISECOND=107,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]

Get Array of Available Locales

With Calendar.getAvailableLocales() method we can use to get list of available locales which can be use as argument of Calendar.getInstance() method.

CalendarExample4.java

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

public class CalendarExample4 {
    public static void main(String... args) {
        Locale[] locales = Calendar.getAvailableLocales();

        for (Locale locale : locales) {
            System.out.print(locale + ", ");
        }
    }
}
The output as below.
ar_AE, ar_JO, ar_SY, hr_HR, fr_BE, es_PA, mt_MT, es_VE, bg, zh_TW, it, ko, uk, lv, da_DK, es_PR, vi_VN, en_US, sr_ME, sv_SE, es_BO, en_SG, ar_BH, pt, ar_SA, sk, ar_YE, hi_IN, ga, en_MT, fi_FI, et, sv, cs, sr_BA_#Latn, el, uk_UA, hu, fr_CH, in, es_AR, ar_EG, ja_JP_JP_#u-ca-japanese, es_SV, pt_BR, be, is_IS, cs_CZ, es, pl_PL, tr, ca_ES, sr_CS, ms_MY, hr, lt, es_ES, es_CO, bg_BG, sq, fr, ja, sr_BA, is, es_PY, de, es_EC, es_US, ar_SD, en, ro_RO, en_PH, ca, ar_TN, sr_ME_#Latn, es_GT, sl, ko_KR, el_CY, es_MX, ru_RU, es_HN, zh_HK, no_NO_NY, hu_HU, th_TH, ar_IQ, es_CL, fi, ar_MA, ga_IE, mk, tr_TR, et_EE, ar_QA, sr__#Latn, pt_PT, fr_LU, ar_OM, th, sq_AL, es_DO, es_CU, ar, ru, en_NZ, sr_RS, de_CH, es_UY, ms, el_GR, iw_IL, en_ZA, th_TH_TH_#u-nu-thai, hi, fr_FR, de_AT, nl, no_NO, en_AU, vi, nl_NL, fr_CA, lv_LV, de_LU, es_CR, ar_KW, sr, ar_LY, mt, it_CH, da, de_DE, ar_DZ, sk_SK, lt_LT, it_IT, en_IE, zh_SG, ro, en_CA, nl_BE, no, pl, zh_CN, ja_JP, de_GR, sr_RS_#Latn, iw, en_IN, ar_LB, es_NI, zh, mk_MK, be_BY, sl_SI, es_PE, in_ID, en_GB,

Convert Calendar to Date

The following Java program to show how to convert a Calendar object into Date object using the Calendar.getTime() method.

CalendarExample5.java

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class CalendarExample5 {
    public static void main(String... args) {
        int year = 2022;
        int month = Calendar.JULY;
        int dayOfMonth = 11;

        Calendar calendar = new GregorianCalendar(year, month, dayOfMonth);
        Date date = calendar.getTime();

        System.out.println(date);
    }
}
The output as below.
Mon Jul 11 00:00:00 ICT 2022

Convert Date to Calendar

The Calendar.setTime() method to set Date value to a Calendar which can be used to convert a Date object into Calendar as following Java program.

CalendarExample6.java

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

public class CalendarExample6 {
    public static void main(String... args) {
        Date date = new Date();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }
}
The output as below.
2022/04/15 22:56:59

Convert Calendar to Milliseconds

The Calendar.getTimeInMillis() to return milliseconds value of a Calendar, this method can be used to convert a Calendar object to a milliseconds value as following Java program.

CalendarExample7.java

import java.util.Calendar;

public class CalendarExample7 {
    public static void main(String... args) {
        Calendar calendar = Calendar.getInstance();

        long milliseconds = calendar.getTimeInMillis();

        System.out.println(milliseconds);
    }
}
The output as below.
1650040757954

Convert Milliseconds to Calendar

The Calendar.setTimeInMillis() method to set a milliseconds value to a Calendar object, we can use this method to convert a milliseconds value to Calendar object as following Java program.

CalendarExample8.java

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

public class CalendarExample8 {
    public static void main(String... args) {
        long milliseconds = 1600000000000L;

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }
}
The output as below.
2020/09/13 19:26:40

Convert Calendar to Instant

In Java we can use the Calendar.toInstant() to convert a Calendar object to Instant object as following example Java program.

CalendarExample9.java

import java.time.Instant;
import java.util.Calendar;

public class CalendarExample9 {
    public static void main(String... args) {
        Calendar calendar = Calendar.getInstance();
        Instant instant = calendar.toInstant();

        System.out.println(instant);
    }
}
The output as below.
2022-04-15T16:47:50.342Z

Get Calendar field values

In Java we can use Calendar.get() method to return value of specified field of a Calendar object as following Java code.

CalendarExample10.java

import java.util.Calendar;

public class CalendarExample10 {
    public static void main(String... args) {
        Calendar calendar = Calendar.getInstance();

        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        int month = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);
        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        int millisecond = calendar.get(Calendar.MILLISECOND);

        System.out.println("Day of month: " + dayOfMonth);
        System.out.println("Month: " + month);
        System.out.println("Year: " + year);
        System.out.println("Hour: " + hour);
        System.out.println("Minute: " + minute);
        System.out.println("Second: " + second);
        System.out.println("Millisecond: " + millisecond);
    }
}
The output as below.
Day of month: 15
Month: 3
Year: 2022
Hour: 11
Minute: 53
Second: 39
Millisecond: 658

Set value for Calendar fields

In Java we can use Calendar.set() method to set value for a specified field of Calendar object as following Java program.

CalendarExample11.java

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

public class CalendarExample11 {
    public static void main(String... args) {
        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.DAY_OF_MONTH, 11);
        calendar.set(Calendar.MONTH, Calendar.JULY);
        calendar.set(Calendar.YEAR, 2022);
        calendar.set(Calendar.HOUR, 7);
        calendar.set(Calendar.MINUTE, 45);
        calendar.set(Calendar.SECOND, 0);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }
}
The output as below.
2022/07/11 07:45:00

Set day month year hour minute seconds of Calendar

With the Calendar.set() method we can also provide date and time as following Java program.

CalendarExample12.java

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

public class CalendarExample12 {
    public static void main(String... args) {
        int dayOfMonth = 11;
        int month = Calendar.JULY;
        int year = 2022;
        int hour = 10;
        int minute = 20;
        int second = 30;

        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(year, month, dayOfMonth);

        Calendar calendar2 = Calendar.getInstance();
        calendar2.set(year, month, dayOfMonth, hour, minute, second);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(calendar1.getTime()));
        System.out.println(simpleDateFormat.format(calendar2.getTime()));
    }
}
The output as below.
2022/07/11 00:05:43
2022/07/11 10:20:30

Clear field values of Calendar

The Calendar class provide clear() method which can be use to set all fields of a Calendar object to undefined.

CalendarExample13.java

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

public class CalendarExample13 {
    public static void main(String... args) {
        Calendar calendar = Calendar.getInstance();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println("Before clear:");
        System.out.println(simpleDateFormat.format(calendar.getTime()));

        calendar.clear();

        System.out.println("After clear:");
        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }
}
The output as below.
Before clear:
2022/04/16 00:10:15
After clear:
1970/01/01 00:00:00

The Calendar.clear() can be used to set a specified field value as following Java program.

CalendarExample14.java

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

public class CalendarExample14 {
    public static void main(String... args) {
        Calendar calendar = Calendar.getInstance();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println("Before clear:");
        System.out.println(simpleDateFormat.format(calendar.getTime()));

        calendar.clear(Calendar.HOUR);
        calendar.clear(Calendar.MINUTE);
        calendar.clear(Calendar.SECOND);

        System.out.println("After clear:");
        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }
}
The output as below.
Before clear:
2022/04/16 00:12:04
After clear:
2022/04/16 00:00:00

Get Display Name of Calendar Fields

With Calendar.getDisplayName() method we can get a string representation of the calendar field in long or short style. In the following Java program we use Calendar.getDisplayName() to get display name of month in English.

CalendarExample15.java

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

public class CalendarExample15 {
    public static void main(String... args) {
        Calendar calendar = Calendar.getInstance();

        String longMonthDisplayName = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH);
        String shortMonthDisplayName = calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.ENGLISH);

        System.out.println(longMonthDisplayName);
        System.out.println(shortMonthDisplayName);
    }
}
The output as below.
April
Apr

Get All Available Calendar Types

With the Calendar.getAvailableCalendarTypes() static method we can get all calendar types that the Calendar supports in current environment.

CalendarExample16.java

import java.util.Calendar;
import java.util.Set;

public class CalendarExample16 {
    public static void main(String... args) {
        Set<String> calendarTypes = Calendar.getAvailableCalendarTypes();

        System.out.println(calendarTypes);
    }
}
The output as below.
[gregory, buddhist, japanese]

Compare two Calendar objects for Equality

In Java we can use the Calendar.equals() method to compare two Calendar objects for equality as following Java code.

CalendarExample17.java

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarExample17 {
    public static void main(String... args) {
        Calendar calendar1 = new GregorianCalendar(2022, Calendar.JULY, 11);
        Calendar calendar2 = new GregorianCalendar(2022, Calendar.JULY, 11);
        Calendar calendar3 = new GregorianCalendar(2022, Calendar.JULY, 12);

        System.out.println(calendar1.equals(calendar2));
        System.out.println(calendar1.equals(calendar3));
    }
}
The output as below.
true
false

Compare two Calendar objects for Ordering

The Calendar.compareTo() method to return value of -1, 0, 1 if the Calendar object is before equal to or later the Calendar object it compare to. We learn how to use Calendar.compareTo() method in the following Java program.

CalendarExample20.java

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarExample20 {
    public static void main(String... args) {
        Calendar calendar1 = new GregorianCalendar(2022, Calendar.JULY, 11);
        Calendar calendar2 = new GregorianCalendar(2022, Calendar.JULY, 11);
        Calendar calendar3 = new GregorianCalendar(2022, Calendar.JULY, 12);

        System.out.println("calendar1 compareTo calendar2: " + calendar1.compareTo(calendar2));
        System.out.println("calendar1 compareTo calendar3: " + calendar1.compareTo(calendar3));
        System.out.println("calendar3 compareTo calendar1: " + calendar3.compareTo(calendar1));
    }
}
The output as below.
calendar1 compareTo calendar2: 0
calendar1 compareTo calendar3: -1
calendar3 compareTo calendar1: 1

Check if a Calendar before another Calendar

Java provides the Calendar.before() to check if a Calendar object is before a specified Calendar object or not. The following Java program to show how to use the Calendar.before() method.

CalendarExample18.java

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarExample18 {
    public static void main(String... args) {
        Calendar calendar1 = new GregorianCalendar(2022, Calendar.JULY, 11);
        Calendar calendar2 = new GregorianCalendar(2022, Calendar.JULY, 10);
        Calendar calendar3 = new GregorianCalendar(2022, Calendar.JULY, 12);

        System.out.println("calendar1 before calendar2: " + calendar1.before(calendar2));
        System.out.println("calendar1 before calendar3: " + calendar1.before(calendar3));
    }
}
The output as below.
calendar1 before calendar2: false
calendar1 before calendar3: true

Check if a Calendar after another Calendar

Java provides the Calendar.after() to check if a Calendar object is after a specified Calendar object or not. The following Java program to show how to use the Calendar.after() method.

CalendarExample19.java

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarExample19 {
    public static void main(String... args) {
        Calendar calendar1 = new GregorianCalendar(2022, Calendar.JULY, 11);
        Calendar calendar2 = new GregorianCalendar(2022, Calendar.JULY, 10);
        Calendar calendar3 = new GregorianCalendar(2022, Calendar.JULY, 12);

        System.out.println("calendar1 after calendar2: " + calendar1.after(calendar2));
        System.out.println("calendar1 after calendar3: " + calendar1.after(calendar3));
    }
}
The output as below.
calendar1 after calendar2: true
calendar1 after calendar3: false

Add or Subtract field values of Calendar

To add or subtract value of specified field of Calendar object we can use the Calendar.add() method as below.

CalendarExample21.java

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

public class CalendarExample21 {
    public static void main(String... args) {
        Calendar calendar = new GregorianCalendar(2022, Calendar.JULY, 11);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println("Before add:");
        System.out.println(simpleDateFormat.format(calendar.getTime()));

        calendar.add(Calendar.DAY_OF_MONTH, 5);
        calendar.add(Calendar.YEAR, -1);

        System.out.println("After add:");
        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }
}
The output as below.
Before add:
2022/07/11 00:00:00
After add:
2021/07/16 00:00:00

Roll up or down a single field unit of Calendar

With the Calendar.roll() method we can add or subtract a single unit of specified field of Calendar object. In the following Java program we use Calendar.roll() method to roll up month and roll down year of a given Calendar object.

CalendarExample22.java

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

public class CalendarExample22 {
    public static void main(String... args) {
        Calendar calendar = new GregorianCalendar(2022, Calendar.JULY, 11);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println("Before roll:");
        System.out.println(simpleDateFormat.format(calendar.getTime()));

        calendar.roll(Calendar.DAY_OF_MONTH, true); // roll up month
        calendar.roll(Calendar.YEAR, false);// roll down year

        System.out.println("After roll:");
        System.out.println(simpleDateFormat.format(calendar.getTime()));
    }
}
The output as below.
Before roll:
2022/07/11 00:00:00
After roll:
2021/07/12 00:00:00

How to clone Calendar object

To clone a given Calendar object we simply use the Calendar.clone() method as following Java code.

CalendarExample23.java

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

public class CalendarExample23 {
    public static void main(String... args) {
        Calendar calendar1 = Calendar.getInstance();

        Calendar calendar2 = (Calendar) calendar1.clone();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(calendar1.getTime()));
        System.out.println(simpleDateFormat.format(calendar2.getTime()));
    }
}
The output as below.
2022/04/16 01:00:58
2022/04/16 01:00:58

Happy Coding 😊

Java LocalDate by Examples

Java LocalTime by Examples

Java LocalDateTime by Examples

Java Calendar using Calendar.Builder by Examples

Java Convert Calendar to Date

Java Convert Calendar to Milliseconds

Java Convert Calendar to Instant

Java Convert Calendar to String

Java Date by Examples

Java Get Current Date and Time