Home >Java >javaTutorial >How to Parse Dates in Java and Resolve the \'java.text.ParseException: Unparseable date\' Error?

How to Parse Dates in Java and Resolve the \'java.text.ParseException: Unparseable date\' Error?

DDD
DDDOriginal
2024-11-19 19:26:02938browse

How to Parse Dates in Java and Resolve the

Parsing Date with Java: Resolving "java.text.ParseException: Unparseable date" Issue

When attempting to parse a date string in Java, it's crucial to ensure that the date format pattern aligns precisely with the input string. In your case, the exception "java.text.ParseException: Unparseable date" suggests a mismatch between the pattern and the input.

Your original pattern, "MMM d, yyyy HH:mm:ss", assumes the date is in the format "Jun 01, 2013 12:53:10". However, the input string includes additional information, notably "Sat" for the day of the week and "IST" for the time zone.

Solution:

To resolve this issue, update the date format pattern to accurately match the input string. The corrected pattern is:

SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);

This pattern includes:

  • EE: Day of the week (e.g., "Sat")
  • MMM: Three-letter month abbreviation (e.g., "Jun")
  • dd: Day of the month (e.g., "01")
  • HH: 24-hour format hour (e.g., "12")
  • mm: Minute (e.g., "53")
  • ss: Second (e.g., "10")
  • z: Time zone abbreviation (e.g., "IST")
  • yyyy: Year (e.g., "2013")

Printing the Desired Format:

Once the date is successfully parsed using the correct pattern, you can obtain the desired output format using a separate SimpleDateFormat instance:

Date parsedDate = sdf.parse(date);
SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss");
System.out.println(print.format(parsedDate));

Notes:

  • To avoid locale-specific issues, explicitly specify Locale.ENGLISH as the locale for the SimpleDateFormat used to parse.
  • If the input string contains an ambiguous time zone abbreviation like "IST," it's recommended to include the full time zone name instead.

The above is the detailed content of How to Parse Dates in Java and Resolve the 'java.text.ParseException: Unparseable date' Error?. 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