Home > Java > javaTutorial > How to Avoid Date String Parsing Exceptions in Java?

How to Avoid Date String Parsing Exceptions in Java?

DDD
Release: 2024-11-13 16:25:03
Original
529 people have browsed it

How to Avoid Date String Parsing Exceptions in Java?

Solving Date String Parsing Exceptions with Java

Parsing date strings into Date objects is a common task in Java programming. However, incorrect patterns can lead to exceptions.

Consider the following example:

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 a java.text.ParseException due to an incorrect pattern. To resolve this issue, the pattern needs to be modified.

In this specific case, the abbreviations for the day (EEE) and month (MMM) should be used instead of the more compact forms (E and MM). Additionally, the pattern should explicitly specify the locale as English. This is because the default locale may not be English on all platforms.

Here's the corrected code:

String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date result = df.parse(target);
Copy after login

This updated code successfully parses the date string and produces the correct Date object:

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

It's important to use the correct pattern and specify the locale to avoid exceptions when parsing date strings.

The above is the detailed content of How to Avoid Date String Parsing Exceptions in Java?. 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