Reputation: 493
Iam using SimpleDateFormat to parse the string and validate the date. But I am not able to validate the year even if I am passing the wrong year.
This is my code:
Date settlementDate = null;
String dd ="02/27/18888";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
dateFormat.setLenient(false);
try {
settlementDate = dateFormat.parse(dd);
} catch (ParseException ex) {
ex.printStackTrace();
}
System.out.println("Date is -->> " + settlementDate);
When I run this program I am getting the output as: Date is -->> Fri Feb 27 00:00:00 PST 18888
But I want it should through an exception as I am passing a 5 digit year. Please help and suggest.
Upvotes: 3
Views: 3804
Reputation: 66637
Here is a text from parse implementation in DateFromat class. Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string. Even though it is not a valid year, it just takes year till valid.
Upvotes: 1
Reputation: 126722
Unfortunately 18888 is a valid year. What do you think will happen in sixteen thousand years time?! You will have to check the year separately if you want to limit the years to four digits.
Upvotes: 1
Reputation: 120286
18888 is a valid year. It's just really far in the future.
From the SimpleDateFormat
documentation:
For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits.
(Emphasis mine)
You'll just have to range check the date to make sure it's within whatever bounds you want.
Upvotes: 3