问题
What's wrong with the following code? It throws a ParseException with error offset 0.
final DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");
df.parse("Thu Jan 23 14:24:47 2014");
回答1:
If you don't specify a Locale
to the formatter when you construct it, it uses your default Locale
which apparently doesn't spell days and months in English.
So specify one to the formatter that does.
final DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.UK);
回答2:
Is your locale "EN"
? If you use English names for the date, make sure you are using that locale
回答3:
SimpleDateFormat is absolutely locale-sensitive. Certain fields, like hours and minutes, are locale-independent.
SimpleDateFormat
also supports localized date and time pattern strings. In these strings, the pattern letters described above may be replaced with other, locale dependent, pattern letters.SimpleDateFormat
does not deal with the localization of text other than the pattern letters; that's up to the client of the class.
Or, you can use the localization-friendly DateFormat#getDateInstance() factory method instead, since:
public SimpleDateFormat(String pattern, Locale locale)
Constructs a
SimpleDateFormat
using the given pattern and the default date format symbols for the given locale. Note: This constructor may not support all locales. For full coverage, use the factory methods in the DateFormat class.
Source: https://stackoverflow.com/a/5174712/2591612
来源:https://stackoverflow.com/questions/23563887/simpledateformat-throws-parseexception-with-error-offset-0