3

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.

Mohit224
  • 443
  • 1
  • 10
  • 24
  • check if year > 9999 after `dateFormat.parse(dd)` and if true, throw an exception.. But 18888 is a valid year :) – Matten Jan 06 '12 at 17:46
  • and WHOOOAAA think about the Year-10000 bug your grand-grand-grand-....-children must solve if you limit your application to 4 digit years! – Matten Jan 06 '12 at 17:49

3 Answers3

3

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.

Community
  • 1
  • 1
Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
1

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.

Borodin
  • 126,100
  • 9
  • 70
  • 144
  • ok cool. this is what i thought but the other thing i started thinking was since i'm passing the yyyy format it should consider the four digit year. I will then check the year separately if this is the case. Thank you for the quick reply. – Mohit224 Jan 06 '12 at 17:47
1

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.

kosa
  • 65,990
  • 13
  • 130
  • 167