The example code below helps you to get all month names as an array of String. The first method, getMonths()
return the full name string while the second method getShortMonths()
return the short name of the month.
package org.kodejava.text;
import java.text.DateFormatSymbols;
import java.util.Locale;
public class MonthNames {
public static void main(String[] args) {
String[] months = new DateFormatSymbols().getMonths();
for (String month : months) {
System.out.println("month = " + month);
}
String[] shortMonths = new DateFormatSymbols().getShortMonths();
for (String shortMonth : shortMonths) {
System.out.println("shortMonth = " + shortMonth);
}
DateFormatSymbols dfs = new DateFormatSymbols(Locale.GERMANY);
String[] germanyMonths = dfs.getMonths();
for (String germanyMonth : germanyMonths) {
System.out.println("germanyMonth = " + germanyMonth);
}
String[] germanyShortMonths = dfs.getShortMonths();
for (String germanyShortMonth : germanyShortMonths) {
System.out.println("germanyShortMonth = "
+ germanyShortMonth);
}
}
}
The results of the code above are:
month = January
month = February
...
month = December
month =
shortMonth = Jan
shortMonth = Feb
...
shortMonth = Dec
shortMonth =
germanyMonth = Januar
germanyMonth = Februar
...
germanyMonth = Dezember
germanyMonth =
germanyShortMonth = Jan
germanyShortMonth = Feb
...
germanyShortMonth = Dez
germanyShortMonth =
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023
Why is there an empty element at the end of the array?
The
DateFormatSymbols
’s methods such asgetMonths()
orgetShortMonths()
shown in the snippet above returns an array of 13 strings. It’s because some calendars system can have 13 months.Because we are working with a system that have 12 months calendars system, it gives us an empty element at the end of the array.
I see. One would think that the implementation of those methods would take into account the calendar system for the default locale. Apparently that’s not the case. It seems like an intern must have written those methods.
Is it possible without empty element at the end of the array?
Hi Venkat,
What about copying the first 12 elements of the array into another array. Something like:
Here am getting months (readGrandChildren method) ascending order but I want calendar order like Jan, Feb, Mar, …., Dec.
Please can anyone help me?