clj-time and Joda Time to pretty-print my son’s age in Clojure

In Clojure’s lein and clj-time to calculate my son’s age I wrote about clj-time to help me calculate my son’s age. What I missed was how to display weeks, days and hours and such in a format like: 4 months and 4 days and 5 hours and 10 minutes.

Konrad Garus pointed out at org.joda.time.format.PeriodFormatterBuilder that would do this.

The following is a possible answer to my question of formatting the age of my youngest son up to minutes. Note how I almost directly copied the Java version to create the Clojure one. Ideas and comments welcome.

(import 'org.joda.time.format.PeriodFormatterBuilder)

(defn format-age [interval]
  (let [builder (doto (PeriodFormatterBuilder.)
                      (.printZeroAlways)
                      (.printZeroRarelyLast)
                      (.appendMonths)
                      (.appendSuffix " month" " months")
                      (.appendSeparator " and ")
                      (.appendDays)
                      (.appendSuffix " day" " days")
                      (.appendSeparator " and ")
                      (.appendHours)
                      (.appendSuffix " hour" " hours")
                      (.appendSeparator " and ")
                      (.appendMinutes)
                      (.appendSuffix " minute" " minutes"))
        formatter (.toFormatter builder)]
    (.print formatter interval)))

(use 'clj-time.core)

(def maksym-birth-date-time (date-time 2011 10 03 17 23))

(def maksym-interval (interval maksym-birth-date-time (now)))

(format-age (.toPeriod maksym-interval))

(in-weeks maksym-interval)

When you run it, it should print out the following output:

user=> (format-age (.toPeriod maksym-interval))
"4 months and 6 days and 4 hours and 25 minutes"
user=> (in-weeks maksym-interval)
19
Be Sociable, Share!
This entry was posted in Languages.

Leave a Reply

%d bloggers like this: