Last Updated: September 09, 2019
· rauh

Parse duration string in clojure (or Java)

(ns x (:import [org.joda.time Period]))

(defn- period-handler
  "Handles duration tags for EDN. Returns the period in milliseconds.
   The format must be in ISO-8601:
   All spaces are ignored and removed prior to parsing.
   Additionally if the parsing fails it will be retried with \"PT\"+in
   (period-handler \"PT 1m\") ;
   (period-handler \"1m 3.53s\") ;"
  (let [s (string/replace in #"[ \t\r\n]" "")]
        (.getMillis (.toStandardDuration (Period/parse s)))
        (catch Exception _ nil))
      (try ; If prev didn't work we append "PT" to the string so we allow strings like "5m 2s"
        (.getMillis (.toStandardDuration (Period/parse (str "PT" s))))
        (catch Exception _ nil)))))