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 meanyyyy
, which is the year.Just change your format to:
The
YYYY
format specifier is rarely used, and when it is used, it should be used in conjunction withE
/u
(day of week name/number) andw
(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 thejava.time
package, and otherwise Joda Time is a much cleaner library thanjava.util.Date
etc.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:
The attempt to parse
strInput1
givesjava.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 thatu
is for year, lowercasey
is for year-of-era and uppercaseY
is for week-based year. Assuming year will always be in the common era (“anno domini”), we can takeu
ory
:Now the code prints:
We can also format the date back into a string, of course:
The result is the string we started out from, as expected:
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 aDate
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.