René Link René Link - 1 year ago 81
Java Question

How to prevent SimpleDateFormat to parse wrong formatted dates?

I use

to parse strings to
objects and I wonder why the results are not what I expect.

For example:

DateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");

Date date = yyyyMMdd.parse("20100725");

works as expected and outputs

Sun Jul 25 00:00:00 CEST 2010


Date date = yyyyMMdd.parse("2010-07-25");

also works and outputs

Mon Dec 07 00:00:00 CET 2009

I expected a
, but it seems that
interpretes the month part
and the day part
as a negative number. First I couldn't figure out how it comes to 7th of december. So I tried another value:

Date date = yyyyMMdd.parse("2010-7-25");

and it outpus

Sun Apr 05 00:00:00 CEST 2009

So it seems that it somehow subtracts
month from the year
which whould be 1th of may, and
days so the result is 5th of april 2009.

Image that you use the pattern
in an service implementation and some client accidentially sends the date as
. You will not get an exception. Instead you will get totally different dates. I guess this is not what you expect.


String clientData = "2010-05-23";

DateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
Date parsedDate = yyyyMMdd.parse(clientData);

System.out.println("Client : " + clientData);
System.out.println("Service : " + yyyyMMdd.format(parsedDate));

Do I miss something?

How do I prevent
to parse 'wrong' dates?

Sure I can use a regular expression to check first, but is there a better way?

Answer Source

Use SimpleDateFormat.setLenient(false); to get an exception. Otherwise it will try to parse the input as best as it can, which is usually wrong.

For some reason they decided that leniency should be true by default, but that is hardly a surprise.

Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download