Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

jframe - How do I check date validity in MM/dd/yyyy in Java?

LocalDateTime dateAndTime = LocalDateTime.now(); //gets current date and time
    
    String birthdateIn = cBirthdate.getText(); //gets birthdate input
    
    SimpleDateFormat mmddyyyy = new SimpleDateFormat("mm/dd/yyyy"); //mm/dd/yyyy formatter
    mmddyyyy.setLenient(false);
    
    try {
        Date stringToDate = mmddyyyy.parse(birthdateIn);
        bLabel.setForeground(Color.green);
        bLabel.setText("Valid Birthdate");
    }
    catch (ParseException e) {
        bLabel.setForeground(Color.red);
        bLabel.setText("Invalid Birthdate");
    }

This is the code I'm using to check for birthdate validity in JFrame, and while the checker works correctly, it validates year when I input a single integer instead of checking if it contains 4 integers. How do I correct it?

Also how do I extract the inputted birthdate to check if the user is below 18 years old?

question from:https://stackoverflow.com/questions/65652029/how-do-i-check-date-validity-in-mm-dd-yyyy-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...