Skip to content

Instantly share code, notes, and snippets.

@djtango
Created November 15, 2017 10:47
Show Gist options
  • Save djtango/30f18a1b5c5117c89cdedd05fee0a192 to your computer and use it in GitHub Desktop.
Save djtango/30f18a1b5c5117c89cdedd05fee0a192 to your computer and use it in GitHub Desktop.
Output clj-time objects into readable clojure
(ns djtango.write-date
"Serialising/deserialsing mixed Clojure/JodaTime data.")
;; I made use of the advice at http://proofbyexample.com/print-and-read-in-clojure.html
;; in writing this file.
;; Make it possible to print joda DateTime instances in re-readable form, for persistence.
(defmethod print-dup org.joda.time.DateTime
[dt out]
(.write out (str "#=" `(org.joda.time.DateTime. ~(.getMillis dt) ~org.joda.time.DateTimeZone/UTC))))
(defmethod print-dup org.joda.time.LocalDate
[ld out]
(.write out (str "#="
`(org.joda.time.LocalDate.
~(.getYear ld)
~(.getMonthOfYear ld)
~(.getDayOfMonth ld)))))
;; Make it possible to print joda Interval instances in re-readable form, for persistence.
(defmethod print-dup org.joda.time.Interval
[value out]
(.write out (str "#=" `(org.joda.time.Interval. ~(.getStartMillis value) ~(.getEndMillis value) ~org.joda.time.DateTimeZone/UTC))))
;; Make it possible to print joda DateTimeZone instances in re-readable form, for persistence.
(defmethod print-dup org.joda.time.DateTimeZone
[value out]
(.write out (str "#=" `(org.joda.time.DateTimeZone/forID ~(.getID value)))))
(defn persist-to-file
"Persist this `value` in the file at this `file-path`."
[value file-path]
(binding
[*print-dup* true]
(spit file-path (with-out-str (pr value)))))
(defn recover-from-file
"Read a persisted value from this `file-path`."
[file-path]
(binding
[*read-eval* true]
(read-string (slurp file-path))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment