Checking for a date or not in Java

Is there any predefined class in Java so that if I pass it a date, it must return if it is a valid date or not? For example, if I go through February 31 of a 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 need a method that will tell me exactly which weekday this particular date is. I went through the Calender class, but I did not understand how to do this.

+5
source share
3 answers

How to check 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 e) {
            return false;
        } catch (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
    }
+14
source

DateFormat # isLenient (false), , :

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".

, , .

+4

You can use this to get the day of the week from the date

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

All Articles