Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Date for different Locals using SimpleDateFormat

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...

like image 595
Dilantha Avatar asked Jun 27 '26 01:06

Dilantha


1 Answers

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
like image 183
A4L Avatar answered Jun 28 '26 15:06

A4L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!