Solving Date String Parsing Exceptions with Java
Parsing date strings into Date objects is a common task in Java programming. However, incorrect patterns can lead to exceptions.
Consider the following example:
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 a java.text.ParseException due to an incorrect pattern. To resolve this issue, the pattern needs to be modified.
In this specific case, the abbreviations for the day (EEE) and month (MMM) should be used instead of the more compact forms (E and MM). Additionally, the pattern should explicitly specify the locale as English. This is because the default locale may not be English on all platforms.
Here's the corrected code:
String target = "Thu Sep 28 20:29:30 JST 2000"; DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH); Date result = df.parse(target);
This updated code successfully parses the date string and produces the correct Date object:
Thu Sep 28 07:29:30 BOT 2000
It's important to use the correct pattern and specify the locale to avoid exceptions when parsing date strings.
The above is the detailed content of How to Avoid Date String Parsing Exceptions in Java?. For more information, please follow other related articles on the PHP Chinese website!