Fastest way to tell if a string is a valid date

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

    0 讨论(0)
  • 2020-12-13 05:36

    Building upon the answer by dfb, you could do a two step hash.

    1. Create a simple object (day,month,year) representing a date. Compute every calendar day for the next 50 years, which should be less than 20k different dates.
    2. Make a regex that confirms if your input string matches yyyyMMdd, but does not check if the value is a valid day (e.g. 99999999 will pass)
    3. The check function will first do a regex, and if that succeeds -- pass it to the hash function check. Assuming your date object is a 8bit + 8bit + 8bit (for year after 1900), then 24 bits * 20k, then the whole hash table should be pretty small... certainly under 500Kb, and very quick to load from disk if serialized and compressed.
    0 讨论(0)
提交回复
热议问题