Boundless
Boundless

Reputation: 2464

Weird date parsing in Java

I am trying to do date validation. When the user enters something like: 2552533 Jan 2012 1340001 this gets parsed as: Wed Sep 03 07:41:00 EDT 9000. Here is my code:

SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy kkmm");
...
Date test;
try {
    test = sdf.parse(dateString);
} catch (Exception e) {
...

Here dateString is a string that I'm trying to parse into a date. If the string isn't a valid date, like: 552533 Jan 2012 1340001, I was hoping for an error to be thrown. What am I doing wrong?

Upvotes: 0

Views: 283

Answers (3)

dtyler
dtyler

Reputation: 1207

As Tudor mentions, SimpleDateFormat does not throw an exception when it fails to parse. One alternative is DateUtils.parseDate90 (javadocs) from the Apache Commons available here.

Upvotes: 0

Tudor
Tudor

Reputation: 62439

SimpleDateFormat.parse does not throw any exception in case of error, it returns null. From the javadoc:

 Returns:
     A Date parsed from the string. In case of error, returns null.  
 Throws:
     NullPointerException - if text or pos is null.

So you can do:

SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy kkmm");
...
Date test = sdf.parse(dateString);
if(test == null) {
   // there was an error
}

Upvotes: 1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Try this (before parsing the actual date):

sdf.setLenient(false);

See also:

Upvotes: 4

Related Questions