In this program if my input date string is "12/03/1956 12:34:99", then also I am getting valid date in sysout.
Output: Valid new date is :Mon Dec 03 12:34:00 IST 1956
My requirement is to show date invalid to user if in input seconds are supplied. My input is valid if it is 12/03/1956 12:34, else invalid if it contains seconds information.
How can I achieve it without using substrings, regex? I can only use SimpleDateFormat.
First of all, you don't need to re-format the Date to show only the year and then parse that to an int. You can use a Calendar for that:
Now, to the problem at hand. This is one of the reasons I don't like the parse(String) methods. They allow trailing characters after the valid input. By using the other parse method, parse(String, ParsePosition), you can prevent this. An added benefit is that you don't need to catch a ParseException:
The parse(String) method only checks for validity. This also checks if the current parse position is directly at the end of the input. If it isn't then there are characters after the valid date.
I have string like "January2011" which can be validated using "MMMMMyyyy" pattern. But, "MMMMMyyyy" pattern will validate "Jan2011" which I don't want.
I can use parse position and the way suggested in above posts, but since my code is generic and am validating other patterns also, I can't do it.
So, is it possible to validate fullmonthYYYY with any pattern in java without using parse position and checking the length of pattern?