Distinguishing between date doesn't exist and bad date format

L

laredotornado

Hi,

I'm using Java 1.6. I have this code for verifying that a date is in
the format "MM/dd/yyyy" ...

SimpleDateFormat sdf = new SimpleDateFormat
(DatePref.DATE_FORMAT);
sdf.setLenient(false);
Date d = sdf.parse((String) value, new ParsePosition(0));
if (d == null) {
LOGGER.error("Failed to parse:" + value);
return;
}

Problem is, if a non-existent date, e.g. "02/29/2011" is passed in, it
also fails parsing. So my question is, how can I distinguish between
a date that doesn't exist and a date that is not in the format I would
like?

Thanks, - Dave
 
E

Eric Sosman

laredotornado said:
Hi,

I'm using Java 1.6. I have this code for verifying that a date is in
the format "MM/dd/yyyy" ...

SimpleDateFormat sdf = new SimpleDateFormat
(DatePref.DATE_FORMAT);
sdf.setLenient(false);
Date d = sdf.parse((String) value, new ParsePosition(0));
if (d == null) {
LOGGER.error("Failed to parse:" + value);
return;
}

Problem is, if a non-existent date, e.g. "02/29/2011" is passed in, it
also fails parsing. So my question is, how can I distinguish between
a date that doesn't exist and a date that is not in the format I would
like?

(Side-issue: Why do you need to?)

// UNTESTED!
Date d = sdf.parse((String) value, new ParsePosition(0));
if (d == null) {
sdf.setLenient(true);
if (sdf.parse((String) value, new ParsePosition(0)) == null)
LOGGER.error("Not a date, not nohow: " + value);
else
LOGGER.error("Get a better calendar: " + value);
sdf.setLenient(false);
}

This is one of those areas where I think I'd do experiments
rather than trying to decipher the JavaDoc.
 
L

laredotornado

     (Side-issue: Why do you need to?)

        // UNTESTED!
        Date d = sdf.parse((String) value, new ParsePosition(0));
        if (d == null) {
            sdf.setLenient(true);
            if (sdf.parse((String) value, new ParsePosition(0)) == null)
                LOGGER.error("Not a date, not nohow: " + value);
            else
                LOGGER.error("Get a better calendar: " + value);
            sdf.setLenient(false);
        }

     This is one of those areas where I think I'd do experiments
rather than trying to decipher the JavaDoc.

Untested but it worked perfectly. 5 stars. Thanks, - Dave
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top