user2534365
user2534365

Reputation: 215

Java Date parsing fail

When I was trying to parse date in Java, both of these line return PhaseException, double-checked and doesn't know what' going on, please help!

Date dateobj = new SimpleDateFormat("MMM dd, yyyy").parse("Nov 12, 1994");
Date timeobj = new SimpleDateFormat("hh:mm a").parse("8:20 pm");

The full trace:

java.text.ParseException: Unparseable date: "Nov 12, 1994"
at java.text.DateFormat.parse(Unknown Source)
at testTime.main(testTime.java:12)

Upvotes: 0

Views: 694

Answers (3)

SparkOn
SparkOn

Reputation: 8946

First thing you code doesnot produces any Exception but still it is always safe to specify the Locale

Like this

Date dateobj = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH)
                                                          .parse("Nov 12, 1994");
Date timeobj = new SimpleDateFormat("hh:mm a", Locale.ENGLISH)
                                                     .parse("8:20 pm");

Upvotes: 3

user2534365
user2534365

Reputation: 215

Thanks to JB Nizet, this error is caused by a different locale setting, adding locale to the simpledateformat works

Upvotes: 0

Makoto
Makoto

Reputation: 106430

Double check the declared throws for DateFormat#parse. It is throwing what's known as a checked exception; this means that even though this exception occurs, you should be able to recover from it.

You must either:

  • Declare it to be thrown (add throws ParseException at the signature of your method), or
  • Wrap the expression in a try...catch block. An example is below.

    Date dateobj = null;
    Date timeobj = null;
    try {
        dateobj = new SimpleDateFormat("MMM dd, yyyy").parse("Nov 12, 1994");
        timeobj = new SimpleDateFormat("hh:mm a").parse("8:20 PM");
    } catch(ParseException e) {
        e.printStackTrace();
    }
    

As it stands with your snippet, if I take either precaution (declaring it to be thrown or catch it myself), then I encounter no further runtime errors.

Upvotes: 0

Related Questions