Hugo already said it:
The best you can do is check if the String
is 00/00/00
and handle it
separately - or try to parse with the setLenient(false)
option and
catch the exception.
What I want to do here is show you how you can skip the outdated (and quite often troublesome) SimpleDateFormat
class and follow the suggestion using the modern Java date and time API.
My preferred solution is checking the date string explicitly:
if (dateFromFile.equals("00/00/00")) {
System.out.println("0000-00-00");
} else {
System.out.println(LocalDate.parse(dateFromFile,
DateTimeFormatter.ofPattern("MM/dd/yy")));
}
I am assuming your string is in a String dateFromFile
.
The other option is you try to parse the string and catch the exception (the modern DateTimeFormatter
isn’t lenient per default):
try {
System.out.println(LocalDate.parse(dateFromFile,
DateTimeFormatter.ofPattern("MM/dd/yy")));
} catch (DateTimeParseException dtpe) {
System.out.println("0000-00-00");
}
One potential advantage is it will also catch cases where the string contains zeroes for unknown fields but isn’t literally equal to 00/00/00
— for example 07/00/17
or 0/0/0
.
Third and poorest option, parse leniently and compare to the date that comes out of 00/00/00
:
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("MM/dd/yy")
.withResolverStyle(ResolverStyle.LENIENT);
LocalDate unknownDateParsed = LocalDate.of(1999, Month.NOVEMBER, 30);
LocalDate date = LocalDate.parse(dateFromFile, parseFormatter);
if (date.equals(unknownDateParsed)) {
System.out.println("0000-00-00");
} else {
System.out.println(date);
}
DateTimeFormatter
assumes 2000–2099 when you give it a two-digit year, so 00/00/00
becomes November 30, 1999 because it is 1 month 1 day before 01/01/2000.
One issue with the last approach is poorer validation: it will let other incorrect dates like for example 05/35/17
or 13/32/45
pass without notice.