How to Handle Date String Parsing Exceptions
Parsing date strings into Date objects can sometimes lead to exceptions, as demonstrated in the following code:
String target = "Thu Sep 28 20:29:30 JST 2000"; DateFormat df = new SimpleDateFormat("E MM dd kk:mm:ss z yyyy"); Date result = df.parse(target);
This code throws the following exception:
java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
The reason for this error is that the pattern used for parsing does not match the format of the date string. Specifically, the pattern expects a 3-letter day abbreviation (EEE) and a 3-letter month abbreviation (MMM), but the date string contains a 2-letter day abbreviation (E) and a full month name (Sep).
To correct the problem, the pattern should be updated to match the format of the date string:
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Additionally, specifying the locale ensures that the day and month abbreviations are interpreted correctly, even if the platform default locale is not English.
Using the corrected pattern, the code now successfully parses the date string and returns a Date object representing the date and time specified in the string, adjusted for the current time zone:
Thu Sep 28 07:29:30 BOT 2000
The above is the detailed content of How to Fix ParseException When Parsing Date Strings?. For more information, please follow other related articles on the PHP Chinese website!