Question
How can I convert the following date string into a Date object in Java? 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, I am encountering a ParseException that states: "Unparseable date -'Thu Sep 28 20:29:30 JST 2000'".
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);
Answer
In Java, parsing date strings into Date objects can often lead to exceptions if the format specified does not match the provided date string. This guide explains how to correctly parse a date string and discusses common errors including the 'Unparseable date' exception.
String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
Date result = df.parse(target); // This should work without throwing an exception.
Causes
- The date format specified in the SimpleDateFormat does not correctly match the input date string, especially concerning the month and hours.
- There could be a discrepancy in recognizing the timezone, such as "JST" in this example.
Solutions
- Ensure that the date format string provided to SimpleDateFormat exactly matches the structure of the date string.
- Use 'hh' for 12-hour clock representation instead of 'kk' for 24-hour clock if your hour is in AM/PM format. This affects parsing when the hour is below 10.
- Validate that the timezone is correctly parsed and recognized by the Java runtime.
Common Mistakes
Mistake: Using the wrong date format specifiers, e.g., using 'kk' instead of 'HH' for hour parsing.
Solution: Change from 'kk' to 'HH' for a 24-hour format.
Mistake: Overlooking case sensitivity in month specifiers such as 'MM' instead of 'MMM'.
Solution: Use 'MMM' for abbreviated month names (e.g., Sep).
Helpers
- Java date parsing
- SimpleDateFormat
- ParseException
- Date object Java
- Java date string conversion