I do some Date test
String INCORRECT_DATE_1 = "101.10.2010";
String dtFormatString_104 = "dd.MM.yyyy";
@Test
public void isValidDate() {
FastDateFormat formatter = FastDateFormat.getInstance(dtFormatString_104);
try {
final Date parse = formatter.parse(INCORRECT_DATE_1);
} catch (java.text.ParseException e) {
return false;
}
return true;
}
I get here true because parse
is 9 January of 2011. How to validate it correctly? I want to get false
here because of the incorrect date.
I use Java 8/17. Before FastDateFormatter we use SimpleDateFormatter, but it looks that library not thread safe, so I have task to change one to another.
Try:
import org.apache.commons.lang3.time.FastDateFormat;
import java.text.ParseException;
import java.util.Date;
public class DateTest {
static final String INCORRECT_DATE_1 = "101.10.2010";
static final String dtFormatString_104 = "dd.MM.yyyy";
public static boolean isValidDate() {
FastDateFormat formatter = FastDateFormat.getInstance(dtFormatString_104);
try {
Date parse = formatter.parse(INCORRECT_DATE_1);
// Check if the input matches the correctly formatted output
String reformatted = formatter.format(parse);
return INCORRECT_DATE_1.equals(reformatted);
} catch (ParseException e) {
return false;
}
}
public static void main(String[] args) {
System.out.println(isValidDate()); // Should print false
}
}
After parsing, it reformats the date and checks if it matches the original input. If 101.10.2010 is parsed as 09.01.2011, the round-trip check (INCORRECT_DATE_1.equals(reformatted)) fails, returning false.