Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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

like image 361
theJava Avatar asked Jul 23 '13 10:07

theJava


People also ask

How to specify Locale in SimpleDateFormat?

Locale loc = new Locale("en", "US"); DateFormat dateFormat = DateFormat. getDateInstance(DateFormat. DEFAULT, loc); As shown in the example above, the getDateInstance method of DateFormat needs two input parameters, the first parameter specifies the DateFormat to use and the second parameter is the locale.

How will you format a date based on a locale after you have obtained a DateFormat object?

To format a date for the current Locale, use one of the static factory methods: myString = DateFormat. getDateInstance(). format(myDate);

What is the default timezone for SimpleDateFormat?

If not specified otherwise, the time zone associated with a new SimpleDateFormat is the default one, corresponding to the time zone reported by the operating system. Consider the following code: SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date date = sdf.


2 Answers

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()); 
like image 137
jasdmystery Avatar answered Sep 22 '22 12:09

jasdmystery


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.

like image 35
kip2 Avatar answered Sep 18 '22 12:09

kip2