EDIT: Your question said “String values in the format of mm/dd/yy”, but I understand from your comments that you meant “my input format is dd/mm/yy as string”, so I have changed the format pattern string in the below code accordingly. Otherwise the code is the same in both cases.
public static Optional<LocalDate> stringToDateLinen(String dateValue) {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yy");
try {
return Optional.of(LocalDate.parse(dateValue, dateFormatter));
} catch (DateTimeParseException dtpe) {
return Optional.empty();
}
}
Try it:
stringToDateLinen("03/01/18")
.ifPresentOrElse(System.out::println,
() -> System.out.println("Could not parse"));
Output:
2018-01-03
I recommend you stay away from SimpleDateFormat
. It is long outdated and notoriously troublesome too. And Date
is just as outdated. Instead use LocalDate
and DateTimeFormatter
from java.time
, the modern Java date and time API. It is so much nicer to work with. A LocalDate
is a date without time of day, so this suites your requirements much more nicely than a Date
, which despite its name is a point in time. LocalDate.toString()
produces exactly the format you said you desired (though the LocalDate
doesn’t have a format in it).
My method interprets your 2-digit year as 2000-based, that is, from 2000 through 2099. Please think twice before deciding that this is what you want.
What would you want to happen if the string cannot be parsed into a valid date? I’m afraid that returning null
is a NullPointerException
waiting to happen and a subsequent debugging session to track down the root cause. You may consider letting the DateTimeParseException
be thrown out of your method (just declare that in Javadoc) so the root cause is in the stack trace. Or even throw an AssertionError
if the situation is not supposed to happen. In my code I am returning an Optional
, which clearly signals to the caller that there may not be a result, which (I hope) prevents any NullPointerException
. In the code calling the method I am using the ifPresentOrElse
method introduced in Java 9. If not using Java 9 yet, use ifPresent
and/or read more about using Optional
elsewhere.
What went wrong in your code?
The other answers are correct: Your format pattern string used for parsing needs to match the input (not your output). The ParseException
was thrown because the format pattern contained hyphens and the input slashes. It was good that you got the exception because another problem is that the order of year, month and day doesn’t match, neither does the number of digits in the year.
Link
- Oracle tutorial: Date Time explaining how to use
java.time
.