ManiSto ManiSto - 2 months ago 6
Java Question

Java DateFormat.SHORT with full year

Is there any way to make

format a date with a full year (eg. 12/12/2010), when using
DateFormat.SHORT
as the pattern? I have to format dates in both en_US and da_DK.

I know I could use
DateFormat.MEDIUM
, but the date have to be formatted using only numbers and separators, and
DateFormat.MEDIUM
for en_US produces something like 'Dec 12, 2010'.

Answer

If both formats are the same, then simply use:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

If they differ:

private static Map<Locale, String> formats = new HashMap<Locale, String>();

static {
    formats.put(new Locale("en_US"), "dd/MM/yyyy");
    formats.put(new Locale("da_DK"), "dd.MM.yyyy");
}

And then instead of using DateFormat.getDateInstance(..) use

new SimpleDateFormat(formats.get(locale)).format(..);