When parsing a date string using SimpleDateFormat in Android, the following error occurs:
java.text.ParseException: Unparseable date: "24 Oct 2016 7:31 pm" (at offset 3)
To resolve the error, it is crucial to explicitly specify a locale when using SimpleDateFormat. This ensures that the date format is interpreted correctly based on the locale's conventions.
In addition, it is highly recommended to switch to the modern Java 8 date and time API, which provides improved functionality and eliminates potential issues with outdated APIs like SimpleDateFormat.
For custom date formats, DateTimeFormatter should be used instead of SimpleDateFormat. It offers case-insensitive parsing, supports multiple locales, and is more flexible overall.
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Main { public static void main(String[] args) { String strDateTime = "24 Oct 2016 7:31 pm"; DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d MMM uuuu h:m a", Locale.ENGLISH); LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf); System.out.println(ldt); } }
Default locales can be problematic when parsing dates, as they vary depending on the system's locale settings. To avoid these issues, always explicitly specify the desired locale.
The above is the detailed content of How to Fix java.text.ParseException When Parsing Dates in Android?. For more information, please follow other related articles on the PHP Chinese website!