Home > Java > javaTutorial > How to Parse a Date String with Abbreviated Day and Month Names in Java?

How to Parse a Date String with Abbreviated Day and Month Names in Java?

Barbara Streisand
Release: 2024-11-17 05:21:03
Original
931 people have browsed it

How to Parse a Date String with Abbreviated Day and Month Names in Java?

Parsing Date Strings into Date Objects

Parsing date strings into Date objects is a common task in programming. However, using the wrong pattern can lead to exceptions.

Problem

The following code snippet attempts to parse the date string "Thu Sep 28 20:29:30 JST 2000" into a Date object:

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

However, this code throws an exception:

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

Solution

The problem lies in the date format pattern. The pattern "E MM dd kk:mm:ss z yyyy" uses the following abbreviations:

  • E for 3-letter day abbreviation
  • MM for 3-letter month abbreviation

However, in the provided date string, the day and month abbreviations are not 3 characters long. To fix this, use the following pattern:

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

This pattern specifies:

  • EEE for 3-letter day abbreviation in English
  • MMM for 3-letter month abbreviation in English

Additional Considerations

Consider using "HH" instead of "kk" for hour of day representation. Refer to the Java documentation for more information on date formatting patterns.

The above is the detailed content of How to Parse a Date String with Abbreviated Day and Month Names 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template