Java Calendar Methods

java.util.Calendar is an abstract class that provides methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, DATE, HOUR, MINUTE, etc. In previous article, we already learn several handy methods in Calendar class, here the summary:

Check below example:

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

public class CalendarRevisitedExample {
    
    public static void main(String[] args) {       
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        
        // create a calendar and set
        Calendar cal = Calendar.getInstance();
        cal.set(2016, 4, 1, 18, 20, 30);

        // Print Calendar's field
        System.out.println("Year            : " + cal.get(Calendar.YEAR));
        System.out.println("Month           : " + cal.get(Calendar.MONTH));
        System.out.println("Is May?         : " + (cal.get(Calendar.MONTH) == Calendar.MAY));
        System.out.println("Day of Month    : " + cal.get(Calendar.DAY_OF_MONTH));
        System.out.println("Day of Week     : " + cal.get(Calendar.DAY_OF_WEEK));
        System.out.println("Is Sunday?      : " + (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY));
        System.out.println("Hour of the Day : " + cal.get(Calendar.HOUR_OF_DAY));
        System.out.println("Minute          : " + cal.get(Calendar.MINUTE));
        System.out.println("Second          : " + cal.get(Calendar.SECOND));
        System.out.println("AM PM           : " + cal.get(Calendar.AM_PM));
        System.out.println("Is AM?          : " + (cal.get(Calendar.AM_PM) == Calendar.AM));
        System.out.println("Is PM?          : " + (cal.get(Calendar.AM_PM) == Calendar.PM));
        System.out.println();
        
        // Displaying date using getTime() 
        System.out.println("Current Date     : " + sdf.format(cal.getTime()));
        
        // Manipulating dates
        Calendar clonedCal = (Calendar) cal.clone();
        clonedCal.add(Calendar.DAY_OF_YEAR, -100);
        System.out.println("100 days ago was : " + sdf.format(clonedCal.getTime()));
        
        cal.add(Calendar.MONTH, 6);
        System.out.println("6 months later is: " + sdf.format(cal.getTime()));
    }
}
                    

Year            : 2016
Month           : 4
Is May?         : true
Day of Month    : 1
Day of Week     : 1
Is Sunday?      : true
Hour of the Day : 18
Minute          : 20
Second          : 30
AM PM           : 1
Is AM?          : false
Is PM?          : true

Current Date     : 01-05-2016 18:20:30
100 days ago was : 22-01-2016 18:20:30
6 months later is: 01-11-2016 18:20:30

In this article, we will explore more Calendar methods that can be applicable when we work with Calendar object.

isLenient() and setLenient()

A Calendar can be either in "lenient" or "non-lenient" mode. If it's in lenient mode, it can accept invalid values (like day=32, month=13) and interpret them somehow. If it's in non-lenient mode and invalid values, are set, a runtime exception will be thrown.

isLenient() will tell you whether the Calendar is in lenient or non-lenient mode, but it will not tell you if the data is valid.

CalendarIsLenientExample.java
import java.util.Calendar;

public class CalendarIsLenientExample {
    
    static void printCalendar(Calendar cal) {
        System.out.println("Calendar is Lenient : " + cal.isLenient());
        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();
    }
        
    public static void main(String[] args) {       
        Calendar cal = Calendar.getInstance();
        
        // Set
        cal.set(1980, 3, 18);
        printCalendar(cal);
                
        cal.set(Calendar.MONTH, 1);  // February
        cal.set(Calendar.YEAR, 1998);
        cal.set(Calendar.DAY_OF_MONTH, 29);
        printCalendar(cal);
        
        cal.setLenient(false);
        cal.set(Calendar.MONTH, 1);  // February
        cal.set(Calendar.YEAR, 1998);
        cal.set(Calendar.DAY_OF_MONTH, 29);
        printCalendar(cal);
    }
}
                    

Calendar is Lenient : true
Calendar's date/time: Fri Apr 18 02:19:55 SGT 1980
Calendar's date     : 18
Calendar's month    : 3
Calendar's year     : 1980

Calendar is Lenient : true
Calendar's date/time: Sun Mar 01 02:19:55 SGT 1998
Calendar's date     : 1
Calendar's month    : 2
Calendar's year     : 1998

Calendar is Lenient : false
Exception in thread "main" java.lang.IllegalArgumentException: MONTH: 1 -> 2
        at java.util.GregorianCalendar.computeTime(Unknown Source)
        at java.util.Calendar.updateTime(Unknown Source)
        at java.util.Calendar.getTimeInMillis(Unknown Source)
        at java.util.Calendar.getTime(Unknown Source)
        at com.dariawan.datetime.CalendarIsLenientExample.printCalendar(CalendarIsLenientExample.java:47)
        at com.dariawan.datetime.CalendarIsLenientExample.main(CalendarIsLenientExample.java:70)

Modify Calendar's Fields

Beside get() and set(...), Calendar have following methods to get and set time in millis:

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

public class CalendarGetSetTimeInMillisExample {
    
    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");
            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 Time In Millis      : " + cal.getTimeInMillis());
            
            long now = System.currentTimeMillis();
            cal.setTimeInMillis(now);
            System.out.println("Calendar's Time In Millis (now): " + cal.getTimeInMillis());
            System.out.println("Calendar's date/time (now)     : " + sdf.format(cal.getTime()));            
        } catch (ParseException ex) {
            System.out.println("ParseException occured: " + ex.getMessage());
        }        
    }
}
                    

Calendar's date/time           : 18-04-1980 15:25:30 JST
Calendar's Time In Millis      : 324887130000
Calendar's Time In Millis (now): 1563467235760
Calendar's date/time (now)     : 19-07-2019 01:27:15 JST

There is another set methods - setWeekDate(...) which set Calendar's time based of "weekly" fields

function setWeekDate(...) result is impacted by function setFirstDayOfWeek(...) and setMinimalDaysInFirstWeek​(...) which we will check later on this article.

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

public class CalendarSetWeekDateExample {
    
    public static void main(String[] args) {       
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
        
        Calendar cal = Calendar.getInstance();
        cal.set(1983, 6, 12);
        System.out.printf("Calendar Date/Time: %s\n", sdf.format(cal.getTime()));
        
        cal.setWeekDate(2019, 25, 4);
        System.out.printf("Calendar Date/Time: %s\n", sdf.format(cal.getTime()));
    }
}
                    

Calendar Date/Time: 12 Jul 1983
Calendar Date/Time: 19 Jun 2019

Working with Time Zone

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

public class CalendarTimeZoneExample {
    
    static void printCalendar(Calendar calendar) {
        SimpleDateFormat sdf = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zzz");

        System.out.printf("Calendar's Date/Time: %s\n", sdf.format(calendar.getTime()));
        System.out.printf("Time Zone ID        : %s\n", calendar.getTimeZone().getID());
        System.out.printf("Time Zone Name      : %s\n", calendar.getTimeZone().getDisplayName());
        System.out.println();
    }
    
    public static void main(String[] args) {               
        Calendar cal1 = Calendar.getInstance();
        cal1.set(1997, 4, 7, 20, 30, 40);
        printCalendar(cal1);
        
        TimeZone tz = TimeZone.getTimeZone("Europe/Copenhagen");
        Calendar cal2 = Calendar.getInstance();
        cal2.setTimeZone(tz);
        cal2.set(1997, 4, 7, 20, 30, 40);
        printCalendar(cal2);
    }
}
                    

Calendar's Date/Time: Wed, 07 May 1997 20:30:40 SGT
Time Zone ID        : Asia/Singapore
Time Zone Name      : Singapore Time

Calendar's Date/Time: Thu, 08 May 1997 02:30:40 SGT
Time Zone ID        : Europe/Copenhagen
Time Zone Name      : Central European Time

You must set Time Zone first before setting another calendar fields.

Adding and Subtracting Calendar's Field Using roll()

Besides add(...) function, there are roll(...) function to add or substract Calendar's field:

  • abstract void roll(int field, boolean up): Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
  • void roll(int field, int amount): Adds the specified (signed) amount to the specified calendar field without changing larger fields.
CalendarRollExample.java
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class CalendarRollExample {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        
        // Creating a calendar 
        Calendar cal = Calendar.getInstance();        
        cal.set(2020, 1, 29);

        // Displaying initial date 
        System.out.println("Date: " + sdf.format(cal.getTime()));

        // increasing date, true indicates add 
        cal.roll(Calendar.DAY_OF_MONTH, true);
        // Displaying the result after operation 
        System.out.println("Date: " + sdf.format(cal.getTime()));

        // Decrementing the date, false indicates subtraction 
        cal.roll(Calendar.DAY_OF_MONTH, false);        
        // Displaying the result after operation 
        System.out.println("Date: " + sdf.format(cal.getTime()));
        
        // increasing month, add 4 
        cal.roll(Calendar.MONTH, 4);
        // Displaying the result after operation 
        System.out.println("Date: " + sdf.format(cal.getTime()));
        
        // increasing date, add 2
        cal.roll(Calendar.DATE, 2);
        // Displaying the result after operation 
        System.out.println("Date: " + sdf.format(cal.getTime()));
    }
}
                    

Date: 29-02-2020
Date: 01-02-2020
Date: 29-02-2020
Date: 29-06-2020
Date: 01-06-2020

Please be careful to use roll(...) function, since this function not changing larger fields. As example above, roll one day after 29-02-2020 will result in 01-02-2020.

Comparing Time

  • boolean after​(Object when)​: Returns whether this Calendar represents a time after the time represented by the specified Object.
  • boolean before(Object when): Returns whether this Calendar represents a time before the time represented by the specified Object.
CalendarAfterBeforeExample.java
import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class CalendarAfterBeforeExample {
    
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
	String strDate = "09-04-2018 04:07:33 PM";
        
        Calendar cal1 = Calendar.getInstance();
        try {
            Date date1 = sdf.parse(strDate);
            cal1.setTime(date1);
            System.out.println("calendar1 time: " + sdf.format(cal1.getTime()));                        
        } catch (ParseException ex) {
            System.out.println("ParseException occured: " + ex.getMessage());
        }
        
        Calendar cal2 = Calendar.getInstance();
        cal2.set(2018, 3, 9, 10, 20, 40);
        System.out.println("calendar2 time: " + sdf.format(cal2.getTime()));
        
        System.out.println("calendar1 after calendar2: " + cal1.after(cal2));
        System.out.println("calendar2 after calendar1: " + cal2.after(cal1));

        System.out.println("calendar1 before calendar2: " + cal1.before(cal2));
        System.out.println("calendar2 before calendar1: " + cal2.before(cal1));
    }
}
                    

calendar1 time: 09-04-2018 04:07:33 PM
calendar2 time: 09-04-2018 10:20:40 AM
calendar1 after calendar2: true
calendar2 after calendar1: false
calendar1 before calendar2: false
calendar2 before calendar1: true

The function will return:

  • value 0 if the time represented by anotherCalendar is equal to the time represented by this Calendar
  • value <0 if the time represented by this Calendar is before the time represented by anotherCalendar
  • value >0 if the time represented by this Calendar is after the time represented by anotherCalendar.
CalendarCompareToExample.java
import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class CalendarCompareToExample {
    
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
	String strDate = "09-04-2018 10:20:40 PM";
        
        Calendar cal1 = Calendar.getInstance();
        try {
            Date date1 = sdf.parse(strDate);
            cal1.setTime(date1);
            System.out.println("calendar1 time: " + sdf.format(cal1.getTime()));                        
        } catch (ParseException ex) {
            System.out.println("ParseException occured: " + ex.getMessage());
        }
        
        Calendar cal2 = Calendar.getInstance();
        cal2.set(2018, 3, 9, 10, 20, 40);
        System.out.println("calendar2 time: " + sdf.format(cal2.getTime()));
        
        Calendar cal3 = Calendar.getInstance();
        cal3.clear();
        cal3.set(2018, 3, 9, 22, 20, 40);
        System.out.println("calendar3 time: " + sdf.format(cal3.getTime()));
        
        System.out.println("calendar1 compareTo calendar2: " + cal1.compareTo(cal2));
        System.out.println("calendar2 compareTo calendar1: " + cal2.compareTo(cal1));
        System.out.println("calendar1 compareTo calendar3: " + cal1.compareTo(cal3));
        System.out.println("calendar2 compareTo calendar3: " + cal2.compareTo(cal3));        
    }
}
                    

calendar1 time: 09-04-2018 10:20:40 PM
calendar2 time: 09-04-2018 10:20:40 AM
calendar3 time: 09-04-2018 10:20:40 PM
calendar1 compareTo calendar2: 1
calendar2 compareTo calendar1: -1
calendar1 compareTo calendar3: 0
calendar2 compareTo calendar3: -1

As you can see from example above, I call clear() for cal3 before set the value. This is because, without clear, although I set from YEAR to SECOND same value for cal3 as in cal1, but another calendar fields (ex: MILLISECOND) still different, so I need to clear it first.

clear() and isSet()

  • void clear(): Sets all the calendar field values and the time value (millisecond offset from the Epoch) of this Calendar undefined.
  • void clear(int field): Sets the given calendar field value and the time value (millisecond offset from the Epoch) of this Calendar undefined.
  • boolean isSet(int field): Determines if the given calendar field has a value set, including cases that the value has been set by internal fields calculations triggered by a get method call.
CalendarClearIsSetExample.java
import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class CalendarClearIsSetExample {
    
    static SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss.SSS a");
        
    static void checkSet(Calendar cal) {
        System.out.println("calendar time   : " + sdf.format(cal.getTime()));   
        System.out.println("YEAR set?       : " + cal.isSet(Calendar.YEAR));
        System.out.println("MONTH set?      : " + cal.isSet(Calendar.MONTH));
        System.out.println("DATE set?       : " + cal.isSet(Calendar.DATE));
        System.out.println("HOUR_OF_DAY set?: " + cal.isSet(Calendar.HOUR_OF_DAY));
        System.out.println("HOUR set?       : " + cal.isSet(Calendar.HOUR));
        System.out.println("MINUTE set?     : " + cal.isSet(Calendar.MINUTE));
        System.out.println("SECOND set?     : " + cal.isSet(Calendar.SECOND));
        System.out.println("MILLISECOND set?: " + cal.isSet(Calendar.MILLISECOND));
        System.out.println("AM_PM set?      : " + cal.isSet(Calendar.AM_PM));
        System.out.println();
    }
    
    public static void main(String[] args) {
        String strDate = "09-11-2015 03:30:45.100 PM";
        
        Calendar cal = Calendar.getInstance();
        try {
            Date date1 = sdf.parse(strDate);
            cal.setTime(date1);                                 
        } catch (ParseException ex) {
            System.out.println("ParseException occured: " + ex.getMessage());
        }
     
        checkSet(cal);
        
        cal.clear(Calendar.YEAR);
        cal.clear(Calendar.DATE);
        cal.clear(Calendar.HOUR_OF_DAY);
        cal.clear(Calendar.HOUR);
        cal.clear(Calendar.MILLISECOND);
        cal.clear(Calendar.AM_PM);
        checkSet(cal);
        
        cal.clear();
        checkSet(cal);
    }
}
                    

calendar time   : 09-11-2015 03:30:45.100 PM
YEAR set?       : true
MONTH set?      : true
DATE set?       : true
HOUR_OF_DAY set?: true
HOUR set?       : true
MINUTE set?     : true
SECOND set?     : true
MILLISECOND set?: true
AM_PM set?      : true

calendar time   : 09-11-1970 12:30:45.000 AM
YEAR set?       : false
MONTH set?      : true
DATE set?       : false
HOUR_OF_DAY set?: false
HOUR set?       : false
MINUTE set?     : true
SECOND set?     : true
MILLISECOND set?: false
AM_PM set?      : false

calendar time   : 01-01-1970 12:00:00.000 AM
YEAR set?       : false
MONTH set?      : false
DATE set?       : false
HOUR_OF_DAY set?: false
HOUR set?       : false
MINUTE set?     : false
SECOND set?     : false
MILLISECOND set?: false
AM_PM set?      : false

I find out that, to set certain value, you need to set several fields altogether. As example above, to change hour value, I need to set both HOUR_OF_DAY and HOUR for it takes effect.

Get Available Calendar Types and Locales

  • static Set<String> getAvailableCalendarTypes(): Returns an unmodifiable Set containing all calendar types supported by Calendar in the runtime environment. Available in Java 8 and above
  • static Locale[] getAvailableLocales(): Returns an array of all locales for which the getInstance methods of this class can return localized instances.
CalendarGetAvailableExample.java
import java.util.Calendar;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Stream;

public class CalendarGetAvailableExample {
    
    public static void main(String[] args) {
        System.out.println("Available Calendar Types:");
        Set<String> calTypes = Calendar.getAvailableCalendarTypes();
        calTypes.stream().forEach(System.out::println);
        System.out.println();
        
        System.out.println("Available Locale:");
        Locale[] locales = Calendar.getAvailableLocales();
        Stream.of(locales).forEach(l -> System.out.printf("%s - %s\n", l.toString(), l.getDisplayName()));
    }
}
                    

Available Calendar Types:
gregory
buddhist
japanese

Available Locale:
 - 
ar_AE - Arabic (United Arab Emirates)
ar_JO - Arabic (Jordan)
ar_SY - Arabic (Syria)
hr_HR - Croatian (Croatia)
fr_BE - French (Belgium)
es_PA - Spanish (Panama)
...
... <purposely truncated>
...
zh - Chinese
mk_MK - Macedonian (Macedonia)
be_BY - Belarusian (Belarus)
sl_SI - Slovenian (Slovenia)
es_PE - Spanish (Peru)
in_ID - Indonesian (Indonesia)
en_GB - English (United Kingdom)

Getting Calendar's Field Display Name(s)

CalendarGetDisplayNamesExample.java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

public class CalendarGetDisplayNamesExample {
    
     static void printMap(Map map) {
        StringBuilder sb = new StringBuilder();
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Entry entry = (Entry) iter.next();
            sb.append(entry.getKey());
            sb.append('=').append('"');
            sb.append(entry.getValue());
            sb.append('"');
            if (iter.hasNext()) {
                sb.append(',').append(' ');
            }
        }
        System.out.println(sb.toString());
        System.out.println();
    }
     
    static void printDisplayNames(Calendar cal, Locale locale) {
         SimpleDateFormat sdf = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zzz");
        Map<String, Integer> map;
        
        // call the getDisplayNames method
        map = cal.getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.SHORT, locale);
        System.out.println("DAY_OF_WEEK - SHORT - " + locale.getDisplayName());
        printMap(map);

        map = cal.getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.LONG, locale);
        System.out.println("DAY_OF_WEEK - LONG - " + locale.getDisplayName());
        printMap(map);

        map = cal.getDisplayNames(Calendar.MONTH, Calendar.SHORT, locale);
        System.out.println("MONTH - SHORT - " + locale.getDisplayName());
        printMap(map);

        map = cal.getDisplayNames(Calendar.MONTH, Calendar.LONG, locale);
        System.out.println("MONTH - LONG - " + locale.getDisplayName());
        printMap(map);
        
        System.out.printf("Calendar's Date/Time   : %s\n", sdf.format(cal.getTime()));
        System.out.printf("Calendar's DAY_OF_WEEK : %s\n", cal.getDisplayName​(Calendar.DAY_OF_WEEK, Calendar.SHORT, locale));
        System.out.printf("Calendar's DAY_OF_WEEK : %s\n", cal.getDisplayName​(Calendar.DAY_OF_WEEK, Calendar.LONG, locale));
        System.out.printf("Calendar's MONTH       : %s\n", cal.getDisplayName​(Calendar.MONTH, Calendar.SHORT, locale));
        System.out.printf("Calendar's MONTH       : %s\n", cal.getDisplayName​(Calendar.MONTH, Calendar.LONG, locale));
    }
    
    public static void main(String[] args) {       
        // create a cal
        Calendar cal1 = Calendar.getInstance();        
        Locale locale1 = Locale.getDefault();
        cal1.set(1997, 4, 7, 20, 30, 40);
        printDisplayNames(cal1, locale1);        

        // change locale
        Locale locale2 = Locale.FRANCE;
        Calendar cal2 = Calendar.getInstance(locale2);
        cal2.set(1997, 4, 7, 20, 30, 40);
        printDisplayNames(cal2, locale2);        
    }
}
                    

DAY_OF_WEEK - SHORT - English (Singapore)
Thu="5", Tue="3", Wed="4", Sat="7", Fri="6", Sun="1", Mon="2"

DAY_OF_WEEK - LONG - English (Singapore)
Monday="2", Thursday="5", Friday="6", Sunday="1", Wednesday="4", Tuesday="3", Saturday="7"

MONTH - SHORT - English (Singapore)
Jul="6", Oct="9", Feb="1", Apr="3", Jun="5", Aug="7", Dec="11", May="4", Nov="10", Jan="0", Mar="2", Sep="8"

MONTH - LONG - English (Singapore)
June="5", October="9", December="11", May="4", September="8", March="2", July="6", January="0", February="1", April="3", August="7", November="10"

Calendar's Date/Time   : Wed, 07 May 1997 20:30:40 SGT
Calendar's DAY_OF_WEEK : Wed
Calendar's DAY_OF_WEEK : Wednesday
Calendar's MONTH       : May
Calendar's MONTH       : May
DAY_OF_WEEK - SHORT - French (France)
mar.="3", jeu.="5", mer.="4", ven.="6", dim.="1", sam.="7", lun.="2"

DAY_OF_WEEK - LONG - French (France)
lundi="2", dimanche="1", vendredi="6", mercredi="4", jeudi="5", samedi="7", mardi="3"

MONTH - SHORT - French (France)
déc.="11", juin="5", mai="4", févr.="1", mars="2", août="7", nov.="10", janv.="0", avr.="3", juil.="6", sept.="8", oct.="9"

MONTH - LONG - French (France)
juin="5", mai="4", septembre="8", mars="2", janvier="0", juillet="6", août="7", novembre="10", octobre="9", décembre="11", février="1", avril="3"

Calendar's Date/Time   : Wed, 07 May 1997 20:30:40 SGT
Calendar's DAY_OF_WEEK : mer.
Calendar's DAY_OF_WEEK : mercredi
Calendar's MONTH       : mai
Calendar's MONTH       : mai

First Day of Week and Minimal Days in First Week

  • int getFirstDayOfWeek(): Gets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.
  • int getMinimalDaysInFirstWeek(): Gets what the minimal days required in the first week of the year are; e.g., if the first week is defined as one that contains the first day of the first month of a year, this method returns 1.
  • void setFirstDayOfWeek(int value): Sets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.
  • void setMinimalDaysInFirstWeek​(int value): Sets what the minimal days required in the first week of the year are; For example, if the first week is defined as one that contains the first day of the first month of a year, call this method with value 1.

setFirstDayOfWeek(...) and setMinimalDaysInFirstWeek​(...) also impacted function setWeekDate(...) .

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

public class CalendarFirstDayOfWeekExample {
    
    public static void main(String[] args) {       
        SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy");
        
        // create a cal
        Calendar cal = Calendar.getInstance();
        cal.set(2019, 2, 3, 14, 20, 45);
        System.out.printf("Calendar Date/Time         : %s\n", sdf.format(cal.getTime()));
        System.out.printf("Calendar Type              : %s\n", cal.getCalendarType());
        System.out.println();
        
        System.out.printf("First Day of Week          : %s\n", cal.getFirstDayOfWeek());
        System.out.printf("First Day of Week == SUNDAY: %s\n", (cal.getFirstDayOfWeek() == Calendar.SUNDAY));
        System.out.printf("Minimal Days in First Week : %s\n", cal.getMinimalDaysInFirstWeek());
        System.out.printf("Week Of Year               : %s\n", cal.get(Calendar.WEEK_OF_YEAR));
        System.out.println();
        
        cal.setWeekDate(2019, 25, 4);
        System.out.printf("Calendar Date/Time         : %s\n", sdf.format(cal.getTime()));
        System.out.println();
        
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.setMinimalDaysInFirstWeek​(7);
        System.out.printf("First Day of Week          : %s\n", cal.getFirstDayOfWeek());
        System.out.printf("First Day of Week == SUNDAY: %s\n", (cal.getFirstDayOfWeek() == Calendar.SUNDAY));
        System.out.printf("First Day of Week == MONDAY: %s\n", (cal.getFirstDayOfWeek() == Calendar.MONDAY));
        System.out.printf("Minimal Days in First Week : %s\n", cal.getMinimalDaysInFirstWeek());
        System.out.printf("Week Of Year               : %s\n", cal.get(Calendar.WEEK_OF_YEAR));
        System.out.println();
        
        cal.setWeekDate(2019, 25, 4);
        System.out.printf("Calendar Date/Time         : %s\n", sdf.format(cal.getTime()));
    }
}
                    

Calendar Date/Time         : Sun Mar 03 14:20:45 SGT 2019
Calendar Type              : gregory

First Day of Week          : 1
First Day of Week == SUNDAY: true
Minimal Days in First Week : 1
Week Of Year               : 10

Calendar Date/Time         : Wed Jun 19 14:20:45 SGT 2019

First Day of Week          : 2
First Day of Week == SUNDAY: false
First Day of Week == MONDAY: true
Minimal Days in First Week : 7
Week Of Year               : 24

Calendar Date/Time         : Wed Jun 26 14:20:45 SGT 2019

Other Methods

  • Instant toInstant(): Converts this object to an Instant.
  • String toString(): Return a string representation of this calendar.
  • int getActualMaximum(int field): Returns the maximum value that the specified calendar field could have, given the time value of thisCalendar.
  • int getActualMinimum​(int field): Returns the minimum value that the specified calendar field could have, given the time value of this Calendar.
  • String getCalendarType(): Returns the calendar type of this Calendar. Available in Java 8 and above.
  • abstract int getGreatestMinimum(int field): Returns the highest minimum value for the given calendar field of this Calendar instance.
  • abstract int getLeastMaximum(int field): Returns the lowest maximum value for the given calendar field of this Calendar instance.
  • abstract int getMaximum(int field): Returns the maximum value for the given calendar field of this Calendar instance.
  • abstract int getMinimum(int field): Returns the minimum value for the given calendar field of this Calendar instance.
  • int getWeeksInWeekYear(): Returns the number of weeks in the week year represented by this Calendar.
  • int getWeekYear(): Returns the week year represented by this Calendar.
  • boolean isWeekDateSupported(): Returns whether this Calendar supports week dates.

Conclusion

In this tutorial, we're continue to explore on how to work with Java's Calendar class. Please check Java GregorianCalendar Methods article for examples of codes using Calendar's methods.