Java Utility Library

Java Calendar - getDisplayNames() Method



The java.util.Calendar.getDisplayNames() method returns a Map containing all names of the calendar field in the given style and locale and their corresponding field values. For example, if this Calendar is a GregorianCalendar, the returned map would contain "Jan" to JANUARY, "Feb" to FEBRUARY, and so on, in the short style in an English locale.

Syntax

public Map<String,Integer> getDisplayNames(int field,
                                           int style,
                                           Locale locale)

Parameters

field Specify the calendar field for which the display names are returned.
style Specify the style applied to the string representation; one of SHORT_FORMAT (SHORT), SHORT_STANDALONE, LONG_FORMAT (LONG), LONG_STANDALONE, NARROW_FORMAT, or NARROW_STANDALONE.
locale Specify the locale for the display names.

Return Value

Returns a Map containing all display names in style and locale and their field values, or null if no display names are defined for field.

Exception

  • Throws NullPointerException, if locale is null
  • Throws IllegalArgumentException, if field or style is invalid, or if this Calendar is non-lenient and any of the calendar fields have invalid values

Example:

In the example below, the java.util.Calendar.getDisplayNames() method returns a Map containing all names of the calendar field in the given style and locale and their corresponding field values.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a Calendar object with specified date
    Calendar Cal = new GregorianCalendar(2015, 1, 25);

    //printing the Calendar
    System.out.println("The Calendar is: " + Cal.getTime());

    //create a new locale  
    Locale loc = new Locale("EN", "US");

    //getting a Map containing all maps for DAY_OF_WEEK field
    Map<String, Integer> MyMap =  
            Cal.getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.SHORT_FORMAT, loc);
    System.out.println("MyMap Contains: " + MyMap);
  }
}

The output of the above code will be:

The Calendar is: Wed Feb 25 00:00:00 UTC 2015
MyMap Contains: {Thu=5, Tue=3, Wed=4, Sat=7, Fri=6, Sun=1, Mon=2}

❮ Java.util - Calendar