Sunday, November 11, 2012

How to display months of the year with Java?

The Calendar is very useful utility class provided by Java for manipulating calender fields. It represents months of the year in integer format starting from 0 and ending with 11, which 0 represents 'January' and 11 represents 'December'. The 'getDisplayName' method of Calendar class returns the string representation of the calendar field value in the given style and locale. If no string representation is applicable, null is returned. 

The following Java program displays months of the year in two formats.

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

public class CalendarUtil {

    public static void main(String[] args) {
        displayMonthsInLongFormat();
        displayMonthsInShortFormat();
    }
 
    private static void displayMonthsInLongFormat() {
  
        Calendar cal = Calendar.getInstance();
  
        System.out.println("Months of the year in long format");
        System.out.println("---------------------------------");
  
        for (int i = 0; i < 12; i++) {
            cal.set(Calendar.MONTH, i);
   
             System.out.println(cal.getDisplayName(Calendar.MONTH, 
                           Calendar.LONG, Locale.ENGLISH));; 
        }
     }
 
     private static void displayMonthsInShortFormat() {
  
         Calendar cal = Calendar.getInstance();
  
         System.out.println("Months of the year in short format");
         System.out.println("---------------------------------");
  
         for (int i = 0; i < 12; i++) {
             cal.set(Calendar.MONTH, i);
   
             System.out.println(cal.getDisplayName(Calendar.MONTH, 
                       Calendar.SHORT, Locale.ENGLISH));; 
         }
     } 
}
The above program will generate the following output.

Months of the year in long format ---------------------------------
January
February
March
April
May
June
July
August
September
October
November
December

Months of the year in short format ---------------------------------
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec

1 comments:

Share

Widgets