Question

I saw this question is asked several places but the given answers are not clear to me. That's why im asking it again.

Is it possible to get the Locale specific date by just passing the Locale argument with same date pattern ? for example how can i do something like this

String pattern = "dd/MM/yyyy";
Date d1 = new Date();
 SimpleDateFormat f1 =  new SimpleDateFormat( pattern , Locale.UK );
 f1.format(d1);
 // formatted date should be in  "dd/MM/yyyy" format

 SimpleDateFormat f2 =  new SimpleDateFormat( pattern , Locale.US );
 f2.format(d1);
 // formatted date should be in "MM/dd/yyyy" format

Above code doesnt give me the expected result. Is there a way to do something like this ?

I have tried using DateFormat factory method. The issue with that is i cannot pass the format pattern. it has some predefined date formats (SHORT,MEDIUM etc)

Thanks in advance...

Was it helpful?

Solution

You could try something like this

@Test
public void formatDate() {
    Date today = new Date();
    SimpleDateFormat fourDigitsYearOnlyFormat = new SimpleDateFormat("yyyy");
    FieldPosition yearPosition = new FieldPosition(DateFormat.YEAR_FIELD);

    DateFormat dateInstanceUK = DateFormat.getDateInstance(DateFormat.SHORT, 
            Locale.UK);
    StringBuffer sbUK = new StringBuffer();

    dateInstanceUK.format(today, sbUK, yearPosition);

    sbUK.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(), 
            fourDigitsYearOnlyFormat.format(today));
    System.out.println(sbUK.toString());

    DateFormat dateInstanceUS = DateFormat.getDateInstance(DateFormat.SHORT,
            Locale.US);
    StringBuffer sbUS = new StringBuffer();
    dateInstanceUS.format(today, sbUS, yearPosition);
    sbUS.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(), 
            fourDigitsYearOnlyFormat.format(today));
    System.out.println(sbUS.toString());
}

It basically formats the date using the style DateFormat#SHORT and catches the location of the year using a FieldPosition object. After that you replace the year with its four digits formart.

Output is:

13/11/2013
11/13/2013

EDIT

Use with any pattern

StringBuffer sb = new StringBuffer();
DateFormat dateInstance = new SimpleDateFormat("yy-MM-dd");
System.out.println(dateInstance.format(today));
dateInstance.format(today, sb, yearPosition);
sb.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(), 
        fourDigitsYearOnlyFormat.format(today));
System.out.println(sb.toString());

Output is:

13-11-13
2013-11-13

OTHER TIPS

Try using this :

DateFormat.getDateInstance(int style, Locale locale)

The java doc for SimpleDataFormat states this :

Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the given locale. Note: This constructor may not support all locales. For full coverage, use the factory methods in the DateFormat class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top