tags:

views:

231

answers:

1

I'm using java.text.SimpleDateFormat to parse strings of the form "yyyyMMdd".

If I try to parse a string with a month greater than 12, instead of failing, it rolls over to the next year. Full runnable repro:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ParseDateTest {

    public static void main(String[] args) throws ParseException {

     SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
     Date result = format.parse("20091504"); // <- should not be a valid date!
     System.out.println(result); // prints Thu Mar 04 00:00:00 CST 2010
    }
 }

I would rather have a ParseException thrown.

Is there any non-hacky way of forcing the exception to happen?. I mean, I don't want to manually check if the month is greater than 12. That's kind of ridiculous.

Thanks for any suggestion.

NOTE: I already know about Joda Time, but I need this done in plain JDK without external libraries.

+7  A: 

You need to make it non-lenient. Thus,

format.setLenient(false);

should do it.

BalusC
Thanks a lot. That did the trick. Amazing how asking questions here gives result faster than searching on google (or I suck at searching :).
Sergio Acosta
+1 for the one liner.
KMan