Skip to content

Instantly share code, notes, and snippets.

@terjesb
Forked from casperc/joda-transit.clj
Created December 2, 2015 14:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terjesb/afc6d82a012e42f19b33 to your computer and use it in GitHub Desktop.
Save terjesb/afc6d82a012e42f19b33 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