DateFormat and Locale

In this chapter you will learn:

  1. How to get all locales supported by DateFormat class
  2. Use Locale with DateFormat

Get all locales

static Locale[] getAvailableLocales() Returns all locales for which the get*Instance methods of this class can return localized instances.

import java.text.DateFormat;
import java.util.Locale;
//j  a  v  a  2  s  .  c om
public class Main{
  public static void main(String args[]) {
    Locale[]  locales = DateFormat.getDateInstance().getAvailableLocales();
    for(Locale l: locales){
      System.out.println(l.getDisplayCountry());
    }
   }
}

The output:

Japan/*j ava2  s  . c o  m*/
Peru

Japan
Panama
Bosnia and Herzegovina
...
...
Oman

Thailand


Sweden
Denmark
Honduras

Use Locale with DateFormat

Locale class stores country specific information. We can use locale to represent different countries. For example, Locale.UK is for the United Kindom, Locale.US represents America. DateFormat is smart enough to format date for each country by looking at the Locale information passed in.

The following code uses the DateFormat together with the Locale and outputs date information in different format for each different country.

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
//  j a v a2 s.c o  m
public class MainClass {
  public static void main(String args[]) {
    Date date = new Date();
    DateFormat df;

    df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.JAPAN);
    System.out.println("Japan: " + df.format(date));

    df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.KOREA);
    System.out.println("Korea: " + df.format(date));

    df = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);
    System.out.println("United Kingdom: " + df.format(date));

    df = DateFormat.getDateInstance(DateFormat.FULL, Locale.US);
    System.out.println("United States: " + df.format(date));
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to parse string to get Date