Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make SimpleDateFormat.parse() fail on invalid dates (e.g. month is greater than 12)

Tags:

java

date

parsing

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.

like image 925
Sergio Acosta Avatar asked Dec 15 '09 06:12

Sergio Acosta


People also ask

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

What is parse in SimpleDateFormat parse do?

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.

How do I declare SimpleDateFormat?

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.


1 Answers

You need to make it non-lenient. Thus,

format.setLenient(false); 

should do it.

like image 196
BalusC Avatar answered Sep 17 '22 19:09

BalusC