7

I know I will always get the following date format from a server.

2017-10-16

To run simpleDateFormat.parse("2017-10-16") in client device, and returns a date to represent year 2017 month October date sixteen

I was wondering, should I use

new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

or

new SimpleDateFormat("yyyy-MM-dd", Locale.US);

I had tested both, they work fine.

Here's the test code I'm using

public class JavaApplication23 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        for (Locale locale : Locale.getAvailableLocales()) {
            Locale.setDefault(locale);

            // This breaks the thing!
            //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

            // This is OK.
            //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

            // This is OK too.
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

            Date date;
            try {
                date = simpleDateFormat.parse("2017-10-16");

                if(
                        date.getYear() != 117 || 
                        date.getMonth() != 9 || 
                        date.getDate() != 16
                ) {
                    System.out.println(locale + " locale having problem to parse " + date);
                }
            } catch (ParseException ex) {
                Logger.getLogger(JavaApplication23.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
            }            
        }
    }    
}

Seem like using Locale.ENGLISH or Locale.US both OK.

However, I afraid I might miss out some edge case.

May I know, is Locale.ENGLISH or Locale.US more suitable to constrct locale independent SimpleDateFormat for string parsing?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

2 Answers2

5

In your case locale does not matter, however you can see difference here:

DateFormat.getDateInstance(DateFormat.SHORT, Locale.US).format(new Date()))
11/10/17

DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK).format(new Date())) 
10/11/17

Note that we need to change country, not language.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 1
    Thanks. I can see your use case, on why country locale is matter. My case is using `parse` method only, and I had used "yyyy-MM-dd" to explicitly specific "month shall come before date". So, I guess for my case, using Locale.ENGLISH will be fine? – Cheok Yan Cheng Oct 11 '17 at 06:42
  • Yes, any local will do provided it uses arabic digits. – Evgeniy Dorofeev Oct 11 '17 at 06:44
0

If you want a locale Independent representation, use ISO 8601. It is understood by all programming languages/frameworks.

Also see here for more details.

Jens
  • 570
  • 3
  • 11