-2

I have the following code to check if a given date is valid

SimpleDateFormat fromformatter = new SimpleDateFormat("MMYY");
fromformatter.setLenient(false);

try {
    fromformatter.parse(dateString);
    valuesQuery.append("'" + dateString+ "',");
} catch (ParseException pe) {
    pe.printStackTrace();
    valuesQuery.append("'notDate" + dateString+ "',");
}

Now, when I get dateString = "1803"; which is not a valid date, no exception is thrown. The date format that is being used here is MMYY.

What am i doing wrong?

Note that a regex will not help me as the date format will change.

keanu
  • 123
  • 9
  • Possible duplicate of [Parse yyyy/mm/dd to epoch timestamp using SimpleDateFormat in java](https://stackoverflow.com/questions/24217408/parse-yyyy-mm-dd-to-epoch-timestamp-using-simpledateformat-in-java) –  Aug 30 '17 at 18:59
  • 2
    `m` is for minutes, `M` is for month: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html –  Aug 30 '17 at 19:00
  • I tried a couple of combinations of MMYY, MMyy. It doesnt catch the exception for 1803 – keanu Aug 30 '17 at 19:08
  • 1
    For me, it works with `MMyy`: it throws `java.text.ParseException: Unparseable date: "1803"` –  Aug 30 '17 at 19:28

2 Answers2

1

"mm" is for minutes. Use "MMyy" instead. No exception is thrown as 18 is a valid value for minutes.

SimpleDateFormat fromformatter = new SimpleDateFormat("MMyy");

Please check: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.

1

java.time

Use the modern java.time classes rather than the troublesome legacy date-time classes.

Specifically use the YearMonth to represent such values. It's parse method will throw an exception for invalid input.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMuu" ) ;
try {
    YearMonth ym = YearMonth.parse( "1803" , f ) ;
} catch ( DateTimeParseException e ) {
    … handle error.
}

TIP: If possible, use standard ISO 8601 formats rather than that peculiar format. For year-month that would be YYYY-MM such as 2017-07.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154