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.
以上是如何避免Java中日期字串解析異常?的詳細內容。更多資訊請關注PHP中文網其他相關文章!