Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/27023189/simpledateformat-warning-to-get-local-formatting-use-getdateinstance-getdatet

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...