views:

678

answers:

3

Hi,

I'm trying to format a date in Java in different ways based on the given locale. For instance I want English users to see "Nov 1, 2009" (formatted by "MMM d, yyyy") and Norwegian users to see "1. nov. 2009" ("d. MMM. yyyy").

The month part works OK if I add the locale to the SimpleDateFormat constructor, but what about the rest?

I was hoping I could add format strings paired with locales to SimpleDateFormat, but I can't find any way to do this. Is it possible or do I need to let my code check the locale and add the corresponding format string?

+3  A: 

Use DateFormat.getDateInstance(int style, Locale locale) instead of creating your own patterns with SimpleDateFormat.

jarnbjo
Thanks, this works OK. I went for DateFormat.LONG which suits my needs the best.BTW, Norwegian locale and DateFormat.MEDIUM is crap(!)
fiskeben
You are right, the strange MEDIUM pattern for Norwegian never occured to me. The weekday is also missing in the FULL format, as opposed to most other locales.
jarnbjo
+1  A: 

Use the style + locale: DateFormat.getDateInstance(int style, Locale locale)

Check http://java.sun.com/j2se/1.5.0/docs/api/java/text/DateFormat.html

Run the following example to see the differences:

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

public class DateFormatDemoSO {
  public static void main(String args[]) {
    int style = DateFormat.MEDIUM;
    //Also try with style = DateFormat.FULL and DateFormat.SHORT
    Date date = new Date();
    DateFormat df;
    df = DateFormat.getDateInstance(style, Locale.UK);
    System.out.println("United Kingdom: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.US);
    System.out.println("USA: " + df.format(date));   
    df = DateFormat.getDateInstance(style, Locale.FRANCE);
    System.out.println("France: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.ITALY);
    System.out.println("Italy: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.JAPAN);
    System.out.println("Japan: " + df.format(date));
  }
}
JuanZe
A: 

DateFormat.getDateInstance(DateFormat.SHORT) should work.

gustafc