Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the year in full when using localization in Java?

private String setDate(int day) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.add(Calendar.DATE, + day);
    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    String formattedDate = df.format(cal.getTime());
    return formattedDate;
}

The above method returns "14/06/12" for Locale.UK and "06/14/12" for Locale.US.

How can I get it to return the year in full, i.e. "14/06/2012" for the US locale and "06/14/2012" for UK locale?

like image 789
Amir Ghahrai Avatar asked Sep 16 '25 15:09

Amir Ghahrai


1 Answers

JHS's answer is almost complete. The only thing needs to be done is to make it work for all locales.

import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Locale;

class ChangeDateFormat
{
    private String setDate(int day, Locale locale) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, +day);
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        if (df instanceof SimpleDateFormat)
        {
            SimpleDateFormat sdf = (SimpleDateFormat) df;
            // To show Locale specific short date expression with full year
            String pattern = sdf.toPattern().replaceAll("y+","yyyy");
            sdf.applyPattern(pattern); 
            return sdf.format(cal.getTime());
        }
        String formattedDate = df.format(cal.getTime());
        return formattedDate;
    }

    public static void main(String[] args)
    {
        ChangeDateFormat cdf = new ChangeDateFormat();        
        System.out.println(cdf.setDate(1, Locale.JAPAN));
    }
}

Following Greg's comments (thanks Greg), here is the relevant note from the javadoc:

"If you want even more control over the format or parsing, (or want to give your users more control), you can try casting the DateFormat you get from the factory methods to a SimpleDateFormat. This will work for the majority of countries; just remember to put it in a try block in case you encounter an unusual one."

like image 52
dragon66 Avatar answered Sep 19 '25 05:09

dragon66