Home > Java > javaTutorial > How to Fix ParseException When Parsing Date Strings?

How to Fix ParseException When Parsing Date Strings?

DDD
Release: 2024-11-15 17:06:03
Original
1053 people have browsed it

How to Fix ParseException When Parsing Date Strings?

How to Handle Date String Parsing Exceptions

Parsing date strings into Date objects can sometimes lead to exceptions, as demonstrated in the following code:

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

This code throws the following exception:

java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
Copy after login

The reason for this error is that the pattern used for parsing does not match the format of the date string. Specifically, the pattern expects a 3-letter day abbreviation (EEE) and a 3-letter month abbreviation (MMM), but the date string contains a 2-letter day abbreviation (E) and a full month name (Sep).

To correct the problem, the pattern should be updated to match the format of the date string:

DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Copy after login

Additionally, specifying the locale ensures that the day and month abbreviations are interpreted correctly, even if the platform default locale is not English.

Using the corrected pattern, the code now successfully parses the date string and returns a Date object representing the date and time specified in the string, adjusted for the current time zone:

Thu Sep 28 07:29:30 BOT 2000
Copy after login

The above is the detailed content of How to Fix ParseException When Parsing Date Strings?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template