The modern Java data & time API defined in JSR-310 came out just about the time this question was asked, so I thought it was about time for an answer using it. For the sake of the example and explanation, let’s try keeping your incorrect format pattern string at first:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-YYYY");
String strInput1 = "29-04-2014";
System.out.println("string 1: " + strInput1);
LocalDate date1 = LocalDate.parse(strInput1, dtf);
System.out.println("date 1: " + date1.toString());
The attempt to parse strInput1 gives java.time.format.DateTimeParseException: Text '29-04-2014' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=29, MonthOfYear=4, WeekBasedYear[WeekFields[SUNDAY,1]]=2014},ISO of type java.time.format.Parsed. On one hand I consider the exception a step forward compared to just yielding an incorrect date, as you experienced. On the other hand the exception message is not that easy to read without a deeper knowledge of the newer classes. The word to notice is “WeekBasedYear”. This is only useful with week numbers, so take it as a sign of what’s wrong. Then compare with the documentation. It says that u is for year, lowercase y is for year-of-era and uppercase Y is for week-based year. Assuming year will always be in the common era (“anno domini”), we can take u or y:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-uuuu");
Now the code prints:
string 1: 29-04-2014
date 1: 2014-04-29
We can also format the date back into a string, of course:
String strInput2 = date1.format(dtf);
System.out.println("string 2: " +strInput2);
The result is the string we started out from, as expected:
string 2: 29-04-2014
Note that the modern API comes with a LocalDate class for a date without time of day. This models your requirement more precisely in this case and avoids all kinds of corner cases that might come out of having to drag the time of day along in a Date object.
Question: can I use this with Java 7? You certainly can. For Java 6 and 7 get the ThreeTen Backport and start using the modern classes.