Last Updated: September 09, 2019
·
1.008K
· 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: http://en.wikipedia.org/wiki/ISO_8601#Durations
   All spaces are ignored and removed prior to parsing.
   Additionally if the parsing fails it will be retried with \"PT\"+in
   Example:
   (period-handler \"PT 1m\") ;
   (period-handler \"1m 3.53s\") ;"
  [in]
  (let [s (string/replace in #"[ \t\r\n]" "")]
    (or
      (try
        (.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)))))