How to parse follow date in Java?

2019-08-02 01:38发布

问题:

Hello i need to parse this string

Sun, 15 Aug 2010 3:50 PM CEST

I'm using SimpleDataFormat in this way

String date = "Sun, 15 Aug 2010 3:50 pm CEST";
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy h:mm a Z");
Date d = formatter.parse(date);

but it throws an exception.

Can you help me please?

Thanks

回答1:

SimpleDateFormat is sensitive to the Locale that is currently set. So it can be that there is a problem when trying to parse the format with your current one. With your constructor it uses Locale.getDefault() to determine the setting.

You could try to create the DateFormat explicitly using the Locale.US via new SimpleDateFormat(pattern, Locale.US) and verify if the problem also exists in that case.



回答2:

This code:

try {
    String date = "Sun, 15 Aug 2010 3:50 pm CEST";
    DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy h:mm a Z");
    Date d = formatter.parse(date);
    System.out.println(formatter.format(d));
} catch (ParseException e) {
    e.printStackTrace();
}

Prints (without any exception):

Sun, 15 Aug 2010 3:50 PM +0200

So I guess something else is your problem... What is the exception you get?



回答3:

I've solved in this way

try {
DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy h:mm a", Locale.US);
Date d = df.parse(date);
bean.setDate(d);

} catch (Exception e) { Logger.error("Error while parsing data"); }

Remove Z from pattern and use Locale.US.

Thanks



回答4:

My code is

try {
    DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy h:mm a Z", Locale.US);
    Date d = df.parse(date);
    bean.setDate(d);
}
catch (Exception e)
{
    Logger.error("Error while parsing data");
}

and exception is

java.text.ParseException: Unparseable date: Mon, 16 Aug 2010 2:20 pm CEST

Thanks



标签: java date format