Fastest way to tell if a string is a valid date

前端 未结 8 1158
故里飘歌
故里飘歌 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:36

     public static int checkIfDateIsExists(String d, String m, String y) {
            Integer[] array30 = new Integer[]{4, 6, 9, 11};
            Integer[] array31 = new Integer[]{1, 3, 5, 7, 8, 10, 12};
    
            int i = 0;
            int day = Integer.parseInt(d);
            int month = Integer.parseInt(m);
            int year = Integer.parseInt(y);
    
            if (month == 2) {
                if (isLeapYear(year)) {
                    if (day > 29) {
                        i = 2; // false
                    } else {
                        i = 1; // true
                    }
                } else {
                    if (day > 28) {
                        i = 2;// false
                    } else {
                        i = 1;// true
                    }
                }
            } else if (month == 4 || month == 6 || month == 9 || month == 11) {
                if (day > 30) {
                    i = 2;// false
                } else {
                    i = 1;// true
                }
            } else {
                i = 1;// true
            }
    
            return i;
        }
    

    if it returns i = 2 means date is invalid and returns 1 if date is valid

提交回复
热议问题