SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates

Android

Android Problem Overview


Issue: Using SimpleDateFormat directly without an explicit locale Id: SimpleDateFormat

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Why is the "To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(), or use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates" error coming on this line.

http://developer.android.com/reference/java/text/SimpleDateFormat.html

Android Solutions


Solution 1 - Android

To remove the warning just add Locale.getDefault() as the second argument while instantiating the date format object. Eg.

 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
					java.util.Locale.getDefault());

Solution 2 - Android

Careful about getDefault though, as it might not be appropriate for all use-cases, especially machine-readable output. From the docs:

> The default locale is not appropriate for machine-readable output. The best choice there is usually Locale.US – this locale is guaranteed to be available on all devices, and the fact that it has no surprising special cases and is frequently used (especially for computer-computer communication) means that it tends to be the most efficient choice too.

Solution 3 - Android

It's a dumb lint warning. If you look at the SimpleDateFormat constructor source code it gets the default locale.

public SimpleDateFormat(String pattern) {
    this(pattern, Locale.getDefault());
}

So adding it in your code is redundant and unnecessarily verbose. Locale.getDefault() is almost always what you want since that is what the user's device is set to. If for some reason you need it to always return, for example, "Monday" no matter what the user's language is set to than you can specify Locale.US but that seems like a rare situation.

The best thing to do is disable the dumb inspection.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontheJavaView Question on Stackoverflow
Solution 1 - AndroidjasdmysteryView Answer on Stackoverflow
Solution 2 - Androidkip2View Answer on Stackoverflow
Solution 3 - AndroidmiguelView Answer on Stackoverflow