Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat warning To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(),

Do i need to be worried about this warning? What if I ignore the warning?
What does this warning mean:
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.
In the 2nd Line of the code below. The App is working fine with the code. I wanted to show date eg, 19 Nov 2014.

public static String getFormattedDate(long calendarTimeInMilliseconds) {     SimpleDateFormat sdfDate = new SimpleDateFormat("d MMM yyyy");  //ON THIS LINE     Date now = new Date();     now.setTime(calendarTimeInMilliseconds);     String strDate = sdfDate.format(now);     return strDate; } 

I think this is a correct way to format date as shown here.

like image 953
Mohammed Ali Avatar asked Nov 19 '14 17:11

Mohammed Ali


People also ask

What is the format of SimpleDateFormat?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.

How do I declare SimpleDateFormat?

Creating a SimpleDateFormat You create a SimpleDateFormat instance like this: String pattern = "yyyy-MM-dd"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); The pattern parameter passed to the SimpleDateFormat constructor is the pattern to use for parsing and formatting of dates.

What is import Java text SimpleDateFormat?

The java. text. SimpleDateFormat class provides methods to format and parse date and time in java. The SimpleDateFormat is a concrete class for formatting and parsing date which inherits java.


1 Answers

You are currently using the SimpleDateFormat(String) constructor. This implies the default locale and as the Locale documentation tells you, be wary of the default locale as unexpected output can be produced on various systems.

You should instead use the SimpleDateFormat(String, Locale) constructor. It is going to take in an additional parameter - the locale you want to use. If you want to make sure the output is machine-readable in a consistent way (always looks the same, regardless of the actual locale of the user), you can pick Locale.US. If you do not care about machine redability, you can explicitly set it to use Locale.getDefault().

Using those on your example code would look something like this:

// for US SimpleDateFormat sdfDate = new SimpleDateFormat("d MMM yyyy", Locale.US);  // or for default SimpleDateFormat sdfDate = new SimpleDateFormat("d MMM yyyy",         Locale.getDefault()); 
like image 188
Valter Jansons Avatar answered Sep 20 '22 14:09

Valter Jansons