Fastest way to tell if a string is a valid date

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

    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.

提交回复
热议问题