Fahim Parkar
Fahim Parkar

Reputation: 31637

Parse Exception in SimpleDateFormat

I am using SimpleDateFormat and I am getting ParseException as shown below.

java.text.ParseException: Unparseable date: "Mon Jul 02 21:56:10 AST 2012"

Code I have have is

    String dateStr = "Mon Jul 02 21:56:10 AST 2012";
    DateFormat readFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy ");

    DateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = null;
    try {
        date = readFormat.parse(dateStr);
    } catch (ParseException e) {
        System.out.println("Error in parsing date ********");
    }

    String formattedDate = "";
    if (date != null) {
        formattedDate = writeFormat.format(date);
    }
    System.out.println("Formatted date is " + formattedDate);

Any idea where I am going wrong?

Update 1

I also tried with

DateFormat readFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy ");
                                                                  ^

but still same exception.

Upvotes: 1

Views: 3329

Answers (2)

JB Nizet
JB Nizet

Reputation: 691755

Your code works (with z, and not Z), as soon as I specify that the date format should use the symbols of the English locale:

SimpleDateFormat readFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
readFormat.setDateFormatSymbols(DateFormatSymbols.getInstance(Locale.ENGLISH));

As per eran, you also have extra space after yyyy: yyyy "). Remove that extra space.

Upvotes: 4

Darth Android
Darth Android

Reputation: 3502

The format code Z is for timezone offset, like -0800, while the format code z is for the written format, such as PST or CST, according to what's described at SimpleDateFormat. Double-check that your parse pattern has the intended capitalization.

Upvotes: 0

Related Questions