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.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
The parse() Method of SimpleDateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position.
Creating a SimpleDateFormat You create a SimpleDateFormat instance like this: String pattern = "yyyy-MM-dd"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); The pattern parameter passed to the SimpleDateFormat constructor is the pattern to use for parsing and formatting of dates.
You need to make it non-lenient. Thus,
format.setLenient(false);
should do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With