Parsing Date Strings into Date Objects
Parsing date strings into Date objects is a common task in programming. However, using the wrong pattern can lead to exceptions.
Problem
The following code snippet attempts to parse the date string "Thu Sep 28 20:29:30 JST 2000" into a Date object:
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);
However, this code throws an exception:
java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
Solution
The problem lies in the date format pattern. The pattern "E MM dd kk:mm:ss z yyyy" uses the following abbreviations:
However, in the provided date string, the day and month abbreviations are not 3 characters long. To fix this, use the following pattern:
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
This pattern specifies:
Additional Considerations
Consider using "HH" instead of "kk" for hour of day representation. Refer to the Java documentation for more information on date formatting patterns.
The above is the detailed content of How to Parse a Date String with Abbreviated Day and Month Names in Java?. For more information, please follow other related articles on the PHP Chinese website!