Saturday, February 28, 2009

Get Week and Month names in Java

More and more applications these days are becoming global. Globalized applications are usually multilingual. Most applications need somewhere a calendar input.The web offers a lot of calendar solutions. These solutions usually allows passing to the calendar information regarding the day and month names. This data can be easily extracted by Java without needing to maintain resources list for all desired languages.

The class that holds all this information is named: DateFormatSymbols. This class accepts the Locale as a parameter. The Locale will determine the language in which the week and month information will be shown.

Here is an example of how to get week names:

public static String[] getShortWeekDays(Locale locale)
{
  String[] weekDays = new DateFormatSymbols(locale).getShortWeekdays();
  String[] retWeekDays = new String[7];
  System.arraycopy(weekDays, 1, retWeekDays, 0, 7);
  return retWeekDays;
}
Note, that the first element in the array was ignored. Java returns the first item as empty, and the actual values are starting from index 1. That is to be correlated with Calendar.SUNDAY which returns the number: 1 rather than: 0. If you will want in some way to do: weekDays[Calendar.SUNDAY], it was smarter to leave the original array untouched.

In the same way it is very simple to get long week days:

String[] weekDays = new DateFormatSymbols(locale).getWeekdays();

Getting the short month names:
public static String[] getShortMonths(Locale locale)
{
  String[] months = new DateFormatSymbols(locale).getShortMonths();
  String retMonths[] = new String[12];
  System.arraycopy(months, 0, retMonths, 0, 12);
  return retMonths;
}

This time the returned original array starts from index: 0, but has an additional last empty element. This code fixes this issue, by ignoring the last element. In months Java has chosen to start the index from: 0 and in weeks from: 1. This is a bit inconsistent, and I believe that there will always be someone that can give a long speech for what were the reasons for choosing this way.

Anyway, here is a simple example application that outputs week and month names in both short and regular formats in US Locale:

public static void main(String[] args) {
  System.out.println(Arrays.toString(getShortWeekDays(Locale.US)));
  System.out.println(Arrays.toString(getLongWeekDays(Locale.US)));
  System.out.println(Arrays.toString(getShortMonths(Locale.US)));
  System.out.println(Arrays.toString(getMonths(Locale.US)));
}

And here is the output for this code:
[Sun, Mon, Tue, Wed, Thu, Fri, Sat]
[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
[Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
[January, February, March, April, May, June, July, August, September, October, November, December]

No comments:

Post a Comment