Home > Java > javaTutorial > body text

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

Susan Sarandon
Release: 2024-11-16 10:45:03
Original
485 people have browsed it

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);
Copy after login

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);
Copy after login

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");
Copy after login

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

System.out.println(print.format(parsedDate));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template