Created
February 13, 2018 17:01
-
-
Save teaforthecat/85ad37a63a74cec5a6a3240df1404378 to your computer and use it in GitHub Desktop.
Protect against hard to catch date corruption
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn date? | |
"Ensure a date string is a date and after a cutoff date. This protects against technically valid but corrupt dates like from a century ago or in the future." | |
([s] | |
;; store the year 10 years from now so we don't have to compute it every call | |
(date? s 2010 `~(+ 10 (clj-time.core/year (clj-time.core/now))))) | |
([s past-cutoff future-cutoff] | |
(try | |
(if-let [d | |
(clj-time.format/parse | |
(clj-time.format/formatter "YYYYMMDD") s)] | |
(and d (> future-cutoff (clj-time.core/year d) past-cutoff))) | |
(catch java.lang.IllegalArgumentException e | |
false) | |
(catch org.joda.time.IllegalFieldValueException e | |
false)))) | |
(comment | |
(date? "10001111") ;;=> false | |
(date? "20111111") ;;=> true | |
(date? "23111111") ;;=> false | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment