I am trying to convert a String into Date... But the return value is wrong.
String startDate = \"2013-07-24\";
Date date = new Date();
try{
DateForm
Day of the month is made using lowercase 'd', and you're using it uppercase...
Change it to:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
at it will work
One issue I see is:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-DD");
should be:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
DD
represents Day in YEAR. Read this for more information on SimpleDateFormat.
Change the DD for dd;
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Modern answer:
String startDate = "2013-07-24";
try {
LocalDate date = LocalDate.parse(startDate);
System.out.println(date);
} catch (DateTimeParseException dtpe) {
System.out.println(dtpe.getMessage());
}
It prints the same as the input string:
2013-07-24
Your string conforms with ISO 8601. This is what the modern Java date & time API known as java.time
or JSR-310 “understands” natively, so there is no need for an explicit formatter. It is also what the toString
methods of the classes generally produce, which is why you get the same output back. If you want output in a different format, use a DateTimeFormatter
.
I recommend leaving the outdated SimpleDateFormat
and friends alone. What you really asked of it was a date that was in July and was the 24th day of the year. Obviously no such date exists, and it’s typical for SimpleDateFormat
to give you some date anyway and pretend all is fine. I cannot count the questions on Stack Overflow that come out of such surprising behaviour of the outdated classes. The modern API is so much nicer to work with and does a much greater effort to tell you when you make mistakes (which we obviously all do).
Replace DD
with dd
to match the date.
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
As per the SimpledateFormat documentation
D Day in year
d Day in month