2
votes

I am trying to validate a date which is actually a string, trying to print it in yyyy/MM/dd format. Here is the code.

String s="2012/12/0390990";
SimpleDateFormat ft = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(ft.format(ft.parse(s))); 

and the output is 3083/05/30. I want to have the validations too. No clue how to proceed.

2

2 Answers

5
votes

It's by default lenient. You need to set it non-lenient before parsing.

ft.setLenient(false);

This will result in a ParseException when an invalid day and/or month is been supplied as compared to the year. Note that this doesn't validate the year itself as basically any number of years is valid. Depending on the concrete functional requirement, you might want to do an additional check on the year, e.g. split string on / and then check if the length of the 1st part is 4.

-2
votes

You might better use a RegExp to validate input,
see for example this answer:
https://stackoverflow.com/a/2149692/1448704

Sebastian