Problem:
When using SimpleDateFormat to parse dates, you may encounter the error "java.text.ParseException: Unparseable date," especially when the locale is not specified.
Explanation:
SimpleDateFormat requires a locale to parse dates correctly. If none is specified, it uses the system's default locale, which may not match the format being parsed.
Solution:
SimpleDateFormat dtfmt = new SimpleDateFormat("dd MMM yyyy hh:mm a", Locale.ENGLISH);
Demo with DateTimeFormatter:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; 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").withLocale(Locale.ENGLISH); LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf); System.out.println(ldt); // prints 2016-10-24T19:31 } }
Note:
The above is the detailed content of Why Does SimpleDateFormat Throw 'Unparseable Date'?. For more information, please follow other related articles on the PHP Chinese website!