Last active
December 2, 2015 14:36
-
-
Save casperc/63917170d0982a6a252a to your computer and use it in GitHub Desktop.
Joda DateTime handler for Transit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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