Originally posted by kri shan: Date d = new (�23/04/2004�); I got java.text.ParseException : UnParseable date �02� when I pass wrong date like �2� ( instead of �02/02/2004�) only. How can I handle this situation ?
First, notice that the java.util.Date class documentation states that the Date constructor you're using has been deprecated, and that using java.text.DateFormat.parse is recommended instead. That said, you might find that working with java.text.SimpleDateFormat, a subclass of DateFormat, is preferrable. I certainly prefer it. So, both "02" and "2" work just fine as month and day-of-month formats. However, I understand that you are trying to figure out turning a single number like "2" into a date. You could just create a SimpleDateFormat object with a pattern that specifies a year only.Note that by default, "2" is turned into the year "0002". If you'd prefer that "2" is interpreted as the year "2002", then note that a SimpleDateFormat has a method called set2DigitYearStart that will come in handy. Of course, this method takes an argument of type Date, and to create a Date, you'll likely want to first create another SimpleDateFormat object.Note that had I created sdf2 with the pattern "yyyy", then the year "2" would still have been interpreted as the year "0002". That's just one of those quirks of working with SimpleDateFormat. It's also worth noting that the current default starting year for two digit years is 1924. So, you could have just created a SimpleDateFormat with the patter "yy", and it would work fine - for now. But what happens in the year 2024? Does "2" become "2102"? I don't know. The above solution would avoid this Y2024 problem. If you're going to allow different formats to be used to represent dates, then you're quite possibly going to have to start making use of a few regular expressions to match patterns, and a few different date formatters to then parse different inputs into dates. Hopefully, you're starting to appreciate that working with dates and the various date formats can start to get messy and complicated fast. As such, remember that the more formats you're going to allow to be used to represent dates in your application, the more complicated it will likely get. Personally, I tend to enforce a single input date format if I'm looking for a simple implementation solution.