Home > Java > javaTutorial > How to Parse Date Strings with Abbreviated Day and Month Names?

How to Parse Date Strings with Abbreviated Day and Month Names?

Patricia Arquette
Release: 2024-12-01 08:12:11
Original
746 people have browsed it

How to Parse Date Strings with Abbreviated Day and Month Names?

Parsing Date Strings into Date Objects

To convert a date string into a Date object, the SimpleDateFormat class provides a parse method. However, if the provided pattern does not match the input date string, a ParseException will be thrown.

Solution

In this case, the input date string includes "Thu" and "Sep," indicating abbreviated day and month names, respectively. The correct pattern should use "EEE" and "MMM" for these elements. Additionally, the locale must be explicitly set to English to avoid locale-specific issues.

The corrected code is:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;

public class DateParser {

    public static void main(String[] args) throws ParseException {
        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);
        System.out.println(result);
    }
}
Copy after login

This code prints the correct Date object, adjusted for the specified timezone:

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

Additional Considerations

When parsing date strings, you may also want to consider using "HH" instead of "kk" for the hour pattern, as it represents 24-hour time notation. Refer to the SimpleDateFormat documentation for more information on valid patterns.

The above is the detailed content of How to Parse Date Strings with Abbreviated Day and Month Names?. 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