Problem:
Parsing a date-time string using SimpleDateFormat fails on a specific device, resulting in a "Unparseable date" error.
Analysis:
SimpleDateFormat requires a Locale parameter to specify the language and cultural conventions for date parsing. If no Locale is specified, the system's default Locale is used. This can lead to parsing inconsistencies on devices with different Locale settings.
Solution:
Detailed Explanation:
The given date-time string ("24 Oct 2016 7:31 pm") is in English. However, if the system's default Locale is not English (e.g., in the case of a French phone), the default SimpleDateFormat instance will fail to parse it.
Java 8 (DateTimeFormatter):
In Java 8 , use DateTimeFormatter with an explicit Locale to parse custom date-time strings. Avoid using the predefined Formatters, which do not accept Locales. For example:
DateTimeFormatter dtf = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendPattern("d MMM uuuu h:m a") .toFormatter(Locale.ENGLISH); LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf);
Java 6/7 (ThreeTen-Backport):
If stuck with Java 6 or Java 7, use ThreeTen-Backport to backport the DateTimeFormatter functionality.
Additional Notes:
The above is the detailed content of Why Does My SimpleDateFormat Fail to Parse Dates, and How Can I Fix It Using Locale and DateTimeFormatter?. For more information, please follow other related articles on the PHP Chinese website!