Tuesday, 10 April 2018

Get all the month names in Java

In this post, you are going to learn.
a.   What is DateFormatSymbols API
b.   How to get an instance of DateFormatSymbols
c.   How to get all the months full & short names using DateFormatSybmols API.
d.   How to get localized month names?

What is DateFormatSymbols API?
'java.text.DateFormatSymbols' class encapsulates localized date-time formatting data. By using this class, you can get
         a. Names of the months,
         b. Short names of the months.
         c. The names and short names of the days of the week, and
         d. The time zone data

How to get an instance of DateFormatSymbols?
DateFormatSymbols class provides below constructors to get an instance of 'DateFormatSymbols' class.
DateFormatSymbols()
DateFormatSymbols(Locale locale)

How to get all the months full & short names using DateFormatSybmols API?
DateFormatSymbols API provides getMonths, getShortMonths APIS to get the month name and short form of the month names.

Find the below working application.

Test.java
package com.sample.test;

import java.text.DateFormatSymbols;

public class Test {

  public static void main(String args[]) throws Exception {
   DateFormatSymbols dateFormatSymbols = new DateFormatSymbols();

   String[] months = dateFormatSymbols.getMonths();
   
   System.out.println("Full Month Names:");
   for(String month : months){
    System.out.println(month);
   }
   
   System.out.println("\nShort Month Names: ");
   String[] shortMonths = dateFormatSymbols.getShortMonths();
   for(String month : shortMonths){
    System.out.println(month);
   }
   
 }
}

Output
Full Month Names:
January
February
March
April
May
June
July
August
September
October
November
December


Short Month Names: 
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec

How to get localized month names?
You should create a DateFormatSymbols instance by specifying the locale.
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(Locale.GERMANY);

Below application print the month names in Germany.


Test.java
package com.sample.test;

import java.text.DateFormatSymbols;
import java.util.Locale;

public class Test {

  public static void main(String args[]) throws Exception {
   DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(Locale.GERMANY);

   String[] months = dateFormatSymbols.getMonths();
   
   System.out.println("Full Month Names:");
   for(String month : months){
    System.out.println(month);
   }
   
   System.out.println("\nShort Month Names: ");
   String[] shortMonths = dateFormatSymbols.getShortMonths();
   for(String month : shortMonths){
    System.out.println(month);
   }
   
 }
}

Output
Full Month Names:
Januar
Februar
März
April
Mai
Juni
Juli
August
September
Oktober
November
Dezember


Short Month Names: 
Jan
Feb
Mär
Apr
Mai
Jun
Jul
Aug
Sep
Okt
Nov
Dez



No comments:

Post a Comment