I would recommend to use the new Date/Time API (java.time
) instead of the legacy classes. Therefore, you can use a DateTimeFormatter
with the necessary pattern to parse birthdateIn
to a LocalDate
object. Afterwards you can check whether the user is below 18 years by using LocalDate#isAfter
in combination with LocalDate.now().minusYears(18)
.
Here is a working example:
String birthdateIn = "01/09/2003"; // change to check boundaries
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
try {
LocalDate birthdate = LocalDate.parse(birthdateIn, formatter);
System.out.println("Valid Birthdate");
if (birthdate.isAfter(LocalDate.now().minusYears(18))) {
System.out.println("not 18 years yet");
} else {
System.out.println("18 years or older");
}
} catch (DateTimeParseException e) {
System.out.println("Invalid Birthdate");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…