user1854772
user1854772

Reputation: 31

Unexplained ParseException for SimpleDateFormat

I am trying to parse dates that appear in the format "01-26-2012 03:07 AM".

I created this SimpleDateFormat:

private static final DateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy hh:mm a");

Yet every time I parse the following:

String date = "01-26-2012 03:07 AM";
Date myDate =  DATE_FORMAT.parse(date.trim()); 

I get a ParseException:

java.text.ParseException: Unparseable date: "01-26-2012 03:07 AM" at java.text.DateFormat.parse(DateFormat.java:337)

Is my SimpleDateFormat string correct? Is there anything else that might be stopping it from parsing?

Upvotes: 3

Views: 429

Answers (2)

anoopelias
anoopelias

Reputation: 9538

It is not correct to use SimpleDateFormat as a static object as it is NOT thread safe. I can't say that is the problem here, but could be a pointer.

Upvotes: 0

assylias
assylias

Reputation: 328568

It is most likely a locale issue. If you try with an English locale for example, it should work:

DateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy hh:mm a", Locale.ENGLISH);

Since you don't specify a locale, the default one for your system is used, and the "AM" might not be parsed correctly.

The code below outputs

myDate = Thu Jan 26 03:07:00 GMT 2012

public static void main(String[] args) throws Exception {
    String date = "01-26-2012 03:07 AM";
    DateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy hh:mm a", Locale.ENGLISH);
    Date myDate = DATE_FORMAT.parse(date.trim());
    System.out.println("myDate = " + myDate);
}

As a side note, if you change the code to Locale.CHINESE for example, you would get a parse exception.

Upvotes: 3

Related Questions