I'm trying to use the parse function of SimpleDateFormat
to turn a String
into a Date
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-YYYY");
String strInput1 = "29-04-2014";
System.out.println("string 1: " + strInput1);
Date date1 = new Date();
try {
date1 = sdf.parse(strInput1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("date 1: " + date1.toString());
String strInput2 = sdf.format(date1);
System.out.println("string 2: " +strInput2);
Date date2 = new Date();
try {
date2 = sdf.parse(strInput2);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("date 2 " + date2);
The output for date1
is Mon Dec 30 00:00:00 GMT 2013
, which is then correctly parsed to 30-12-2014
.
I assume the mistake is somewhere when sdf
is initialized.
You're using YYYY
which is the week year. You mean yyyy
, which is the year.
Just change your format to:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
The YYYY
format specifier is rarely used, and when it is used, it should be used in conjunction with E
/u
(day of week name/number) and w
(week of week year).
Note that you should consider setting the time zone of your SimpleDateFormat
as well... additionally, if you're using Java 8, use the java.time
package, and otherwise Joda Time is a much cleaner library than java.util.Date
etc.
See more on this question at Stackoverflow