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
If java.util.Date class is lack of internationalization support, Calendar on contrary provides internationalization support. Beside that, there are a set of calendar fields (YEAR, MONTH, DATE, HOUR, MINUTE, SECOND, MILLISECOND, etc) available, allowing us to access and manipulating them. Using Calendar, we can do "operation" like get the date of the next week, back thirty minutes before, etc.
Calendar class is abstract and cannot be instantiate. To get an instance of an implementation subclass, we must use the static method Calendar.getInstance()
.
- static Calendar getInstance(): Gets an instance of Calendar's concrete subclass using the default time zone and locale.
- static Calendar getInstance(Locale aLocale): Gets an instance of Calendar's concrete subclass using the default time zone and specified locale.
- static Calendar getInstance(TimeZone zone): Gets an instance of Calendar's concrete subclass using the specified time zone and default locale.
- static Calendar getInstance(TimeZone zone, Locale aLocale): Gets an instance of Calendar's concrete subclass with the specified time zone and locale.
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(): Returns what is 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, the first day of the week is MONDAY, so getFirstDayOfWeek()
will return 2.
Conversion between Calendar and Date
As per our example above, we can use getTime()
and setTime()
to convert between Calendar and Date.
- Date getTime(): Get a Date object that representing this Calendar's time value (millisecond offset from the Epoch").
- void setTime(Date date): Set Calendar's time with the given Date.
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
- int get(int field): Returns the value of the given calendar field.
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
- void set(int field, int value): Sets the given Calendar field with the given value.
- void set(int year, int month, int date): Sets the values of the Calendar's YEAR, MONTH, and DAY_OF_MONTH with the given values.
- void set(int year, int month, int date, int hourOfDay, int minute): Sets the values of the Calendar's YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, and MINUTE with the given values.
- void set(int year, int month, int date, int hourOfDay, int minute, int second): Sets the values of the Calendar's YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, MINUTE, and SECOND with the given values.
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 do subtraction from the fields, set the time amount with negative value.
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 an implementation subclass of Calendar, and provides the standard calendar system used by most of the world. Static method Calendar.getInstance()
will return an implementation class java.util.GregorianCalendar for most locale, except JapaneseImperialCalendar for Japanese ("ja_JP_JP_#u-ca-japanese") and BuddhistCalendar for Thai ("th_TH").
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:
- GregorianCalendar(): Constructs a default GregorianCalendar using the current time in the default time zone with the default FORMAT locale.
- GregorianCalendar(int year, int month, int dayOfMonth): Constructs with the given year, month, and dayOftheMonth in the default time zone with the default FORMAT locale.
- GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute): Constructs with the given date set (year, month, and dayOftheMonth) and time set (hourOfDay and minute) in the default time zone with the default FORMAT locale.
- GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second): Constructs with date set (year, month, and dayOftheMonth) and time set (hourOfDay, minute, and second) in the default time zone with the default FORMAT locale.
- GregorianCalendar(Locale aLocale): Constructs based on the current time in the default time zone with the given locale.
- GregorianCalendar(TimeZone zone): Constructs based on the current time in the given time zone with the default FORMAT locale.
- GregorianCalendar(TimeZone zone, Locale aLocale): Constructs based on the current time in the given time zone with the given locale.
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. We can explicitly using one of GregorianCalendar's constructor to get an instance of GregorianCalendar. But, it's advisable to let the JVM choose the right kind of Calendar based on the locale using the static method Calendar.getInstance()
.
Method getTime() and setTime() is used to convert between Calendar and Date.