SimpleDateFormat throws ParseException With Error

2020-04-16 02:09发布

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

3条回答
别忘想泡老子
2楼-- · 2020-04-16 02:14

Is your locale "EN"? If you use English names for the date, make sure you are using that locale

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-04-16 02:27

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

查看更多
SAY GOODBYE
4楼-- · 2020-04-16 02:32

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);
查看更多
登录 后发表回答