Skip to content
Advertisement

Checking if a date exists or not in Java

Is there any predefined class in Java such that, if I pass it a date it should return if it is a valid date or not? For example if I pass it 31st of February of some year, then it should return false, and if the date exists then it should return me true, for any date of any year.

And I also want a method that would tell me what weekday this particular date is. I went through the Calender class but I didn’t get how to do this.

Advertisement

Answer

How to Validate a Date in Java

private static boolean isValidDate(String input) {
    String formatString = "MM/dd/yyyy";
    
    try {
        SimpleDateFormat format = new SimpleDateFormat(formatString);
        format.setLenient(false);
        format.parse(input);
    } catch (ParseException | IllegalArgumentException e) {
        return false;
    }

    return true;
}

public static void main(String[] args){
    System.out.println(isValidDate("45/23/234")); // false
    System.out.println(isValidDate("12/12/2111")); // true
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement