Java Utility Library

Java Calendar - getDisplayName() Method



The java.util.Calendar.getDisplayName() method returns the string representation of the calendar field value in the given style and locale. If no string representation is applicable, null is returned.

For example, if this Calendar is a GregorianCalendar and its date is 2005-01-01, then the string representation of the MONTH field would be "January" in the long style in an English locale or "Jan" in the short style. However, no string representation would be available for the DAY_OF_MONTH field, and this method would return null.

Syntax

public String getDisplayName(int field,
                             int style,
                             Locale locale)

Parameters

field Specify the calendar field for which the string representation is 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 string representation (any calendar types specified by locale are ignored).

Return Value

Returns the string representation of the given field in the given style, or null if no string representation is applicable.

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.getDisplayName() method is used to get the string representation of the calendar field value in the specified style and locale.

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 the string representation of MONTH field
    String info = Cal.getDisplayName(Calendar.MONTH, Calendar.LONG_FORMAT, loc);
    System.out.println("Month is: " + info);
  }
}

The output of the above code will be:

The Calendar is: Wed Feb 25 00:00:00 UTC 2015
Month is: February

❮ Java.util - Calendar