Fastest way to tell if a string is a valid date

前端 未结 8 1142
故里飘歌
故里飘歌 2020-12-13 04:52

I am supporting a common library at work that performs many checks of a given string to see if it is a valid date. The Java API, commons-lang library, and JodaTime all have

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 05:35

    I think that the better way to know if a certain date is valid is defining a method like:

    public static boolean isValidDate(String input, String format) {
        boolean valid = false;
    
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(format);
            String output = dateFormat.parse(input).format(format);
            valid = input.equals(output); 
        } catch (Exception ignore) {}
    
        return valid;
    }
    

    On one hand the method checks the date has the correct format , and on the other hand checks the date corresponds to a valid date . For example, the date "2015/02/29" will be parsed to "2015/03/01", so the input and output will be different, and the method will return false.

提交回复
热议问题