简体   繁体   中英

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.

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
}

The key is to call DateFormat#isLenient( false ) so it won't roll values that are out of range during parsing:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.parse("2010-02-31"); //=> Ok, rolls to "Wed Mar 03 00:00:00 PST 2010".
format.setLenient(false);
format.parse("2010-02-31"); //=> Throws ParseException "Unparseable date".

Of course, you can use any actual date format you require.

You can use this to get weekday from the date

 Calendar currentDate = Calendar.getInstance(); //or your specified date. int weekDay = currentDate.get(Calendar.DAY_OF_WEEK);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM