Skip to content

Instantly share code, notes, and snippets.

@teaforthecat
Created February 13, 2018 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teaforthecat/85ad37a63a74cec5a6a3240df1404378 to your computer and use it in GitHub Desktop.
Save teaforthecat/85ad37a63a74cec5a6a3240df1404378 to your computer and use it in GitHub Desktop.
Protect against hard to catch date corruption
(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