Home >Java >javaTutorial >How to Fix \'java.text.ParseException: Unparseable date\' When Parsing Dates with Additional Information?

How to Fix \'java.text.ParseException: Unparseable date\' When Parsing Dates with Additional Information?

Susan Sarandon
Susan SarandonOriginal
2024-11-16 10:45:03645browse

How to Fix

Resolving "java.text.ParseException: Unparseable date" Exception

The "java.text.ParseException: Unparseable date" exception occurs when the SimpleDateFormat object attempts to parse an input string that does not match its specified pattern. In this case, the input string "Sat Jun 01 12:53:10 IST 2013" cannot be parsed using the pattern "MMM d, yyyy HH:mm:ss" because the input string includes additional information such as the day of the week (Sat) and the time zone (IST).

Solution:

To solve this issue, you need to adjust both the date parsing and printing.

Date Parsing:

  1. Create a SimpleDateFormat object with a pattern that matches the input string. In this case, use the following pattern:
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);

This pattern includes the day of the week (EE), month (MMM), day of the month (dd), hours (HH), minutes (mm), seconds (ss), time zone (z), and year (yyyy). You can customize this pattern based on your specific input string format.

  1. Parse the input string using the created SimpleDateFormat object:
Date parsedDate = sdf.parse(date);

Date Printing:

After parsing the date, you need to format the date to match your desired output. Create a second SimpleDateFormat object with the desired pattern:

SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss");

Then, format the parsed date using the "print" SimpleDateFormat object:

System.out.println(print.format(parsedDate));

Additional Notes:

  • Include the locale in the SimpleDateFormat constructor. This ensures that the date is parsed and printed according to the correct cultural conventions.
  • Use the proper time zone name in the input string instead of ambiguous time zone abbreviations like "IST."

The above is the detailed content of How to Fix \'java.text.ParseException: Unparseable date\' When Parsing Dates with Additional Information?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn