Skip to content

Instantly share code, notes, and snippets.

@casperc
Last active December 2, 2015 14:36
Show Gist options
  • Save casperc/63917170d0982a6a252a to your computer and use it in GitHub Desktop.
Save casperc/63917170d0982a6a252a to your computer and use it in GitHub Desktop.
Joda DateTime handler for Transit
;; Adds support to Transit for emitting Joda DateTimes in the same format as standard java.util.Date.
;; Dependencies: [clj-time "0.9.0"] and [com.cognitect/transit-clj "0.8.259"] (newer version will likely still work)
(require '[cognitect.transit :as transit])
(require '[clj-time.coerce :as coerce])
(import '[java.io ByteArrayOutputStream])
(def ^:private joda-time-verbose-handler
(transit/write-handler
(constantly "t")
(fn [v] (-> v coerce/to-date .getTime))
(fn [v] (coerce/to-string v))))
(def ^:private joda-time-handler
(transit/write-handler
(constantly "m")
(fn [v] (-> v coerce/to-date .getTime))
(fn [v] (-> v coerce/to-date .getTime .toString))
joda-time-verbose-handler))
(def custom-transit-handlers {org.joda.time.DateTime joda-time-handler})
(defn emit-transit
"Allowed types: :json :json-verbose :msgpack. Returns a ByteArrayOutputStream."
[data type]
(let [buffer (ByteArrayOutputStream. 4096)]
(transit/write
(transit/writer buffer type {:handlers custom-transit-handlers})
data)
buffer))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment