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;
// ja  va 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:

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;
/*from   jav  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
Home » Java Tutorial » Date, Time, Calendar, TimeZone

Date

    Date class
    Date comparison
    Converting date value
    DateFormat class
    Format time
    DateFormat and Locale
    Convert String to Date

Calendar

    Calendar class
    Calendar date time getter
    Calendar set hour,minute,second
    Calendar calculation
    Calendar comparison
    Calendar properties
    GregorianCalendar

TimeZone

    TimeZone
    TimeZone ID and display name
    TimeZone daylight saving

DateFormat

    DateFormat class
    Format time
    DateFormat and Locale
    Convert String to Date
    SimpleDateFormat
    Parse date string into Date object
    SimpleDateFormat day format
    SimpleDateFormat Hour Time format
    SimpleDateFormat format minute
    SimpleDateFormat to format month
    SimpleDateFormat to format second value
    SimpleDateFormat to format TimeZone
    SimpleDateFormat to format year
    SimpleDateFormat to combine formatting flags