Skip to content

Instantly share code, notes, and snippets.

@AlexBaranosky
Created October 16, 2012 10:13
Show Gist options
  • Save AlexBaranosky/3898489 to your computer and use it in GitHub Desktop.
Save AlexBaranosky/3898489 to your computer and use it in GitHub Desktop.
Clojure joda DateTime instant reader
(ns groupon.joda-instant-reader
(:require [clojure.instant :as i])
(:import org.joda.time.DateTime))
(defmethod print-method org.joda.time.DateTime
[^org.joda.time.DateTime d ^java.io.Writer w]
(#'i/print-date (java.util.Date. (.getMillis d)) w))
(defmethod print-dup org.joda.time.DateTime
[^org.joda.time.DateTime d ^java.io.Writer w]
(#'i/print-date (java.util.Date. (.getMillis d)) w))
(defn construct-date-time [years months days hours minutes seconds nanoseconds
offset-sign offset-hours offset-minutes]
(DateTime. (.getTimeInMillis (#'i/construct-calendar years months days
hours minutes seconds 0
offset-sign offset-hours offset-minutes))))
(def read-instant-date-time
"To read an instant as an org.joda.time.DateTime, bind *data-readers* to a
map with this var as the value for the 'inst key."
(partial i/parse-timestamp (i/validated construct-date-time)))
(defmacro with-joda-time-reader [& body]
`(binding [*data-readers* (assoc *data-readers* 'inst read-instant-date-time)]
~@body))
@ragnard
Copy link

ragnard commented Feb 8, 2013

Hopefully saving anyone seeing this some time:
the with-joda-time-reader macro is actually subtly wrong, see my fork for fix:
https://gist.github.com/ragnard/4738185

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment