Skip to content

Instantly share code, notes, and snippets.

@qerub
Created January 18, 2014 00:29
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 qerub/8484305 to your computer and use it in GitHub Desktop.
Save qerub/8484305 to your computer and use it in GitHub Desktop.
Summing time durations (given as a string) with Clojure and Joda-Time
;; lein try joda-time org.clojure/algo.generic
;; Let's first shave the parsing yak:
(import (org.joda.time.format PeriodFormatterBuilder))
(def h:m-formatter
(-> (PeriodFormatterBuilder.)
(.appendHours)
(.appendSeparator ":")
(.appendMinutes)
(.toFormatter)))
(defn parse-h:m [str]
(-> h:m-formatter
(.parsePeriod str)
(.toStandardDuration)))
;; ...and then the addition yak:
(require '[clojure.algo.generic.arithmetic :as g])
(import (org.joda.time Duration))
(defmethod g/+ [Duration Duration] [a b] (.plus a b))
;; ...and now the actual task:
(require '[clojure.string :refer [split]])
(def input (split "4:30 1:35 3:35 1:18" #"\s+"))
(def sum (->> input
(map parse-h:m)
(reduce g/+)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment