Skip to content
Snippets Groups Projects
Commit 4093dbdc authored by Allen Gilliland's avatar Allen Gilliland
Browse files

add a protocol specifically for formatting ISO8601 date times w/ timezone and test it.

parent 8a5d65e6
No related branches found
No related tags found
No related merge requests found
......@@ -4,6 +4,7 @@
(clojure [pprint :refer [pprint]]
[string :as s])
[clojure.tools.logging :as log]
[clj-time.core :as t]
[clj-time.coerce :as coerce]
[clj-time.format :as time]
[colorize.core :as color]
......@@ -62,8 +63,30 @@
(pprint-to-str (sort (keys time/formatters)))))))))
(defprotocol ISO8601
"Protocol for converting objects to ISO8601 formatted strings."
(->ISO8601DateTime ^String [this timezone-id]
"Coerce object to an ISO8601 date-time string such as \"2015-11-18T23:55:03.841Z\" with a given TIMEZONE."))
(def ^:private ISO8601Formatter
;; memoize this because the formatters are static. they must be distinct per timezone though.
(memoize (fn [timezone-id]
(if timezone-id (time/with-zone (time/formatters :date-time) (t/time-zone-for-id timezone-id))
(time/formatters :date-time)))))
(extend-protocol ISO8601
nil (->ISO8601DateTime [_ _] nil)
java.util.Date (->ISO8601DateTime [this timezone-id] (time/unparse (ISO8601Formatter timezone-id) (coerce/from-date this)))
java.sql.Date (->ISO8601DateTime [this timezone-id] (time/unparse (ISO8601Formatter timezone-id) (coerce/from-sql-date this)))
java.sql.Timestamp (->ISO8601DateTime [this timezone-id] (time/unparse (ISO8601Formatter timezone-id) (coerce/from-sql-time this)))
org.joda.time.DateTime (->ISO8601DateTime [this timezone-id] (time/unparse (ISO8601Formatter timezone-id) this)))
;;; ## Date Stuff
(defn is-temporal? [v]
(and v (contains? #{:java.sql.Timestamp :java.sql.Date :java.util.Date :org.joda.time.DateTime} (keyword (.getName (type v))))))
(defn new-sql-timestamp
"`java.sql.Date` doesn't have an empty constructor so this is a convenience that lets you make one with the current date.
(Some DBs like Postgres will get snippy if you don't use a `java.sql.Timestamp`)."
......
......@@ -15,6 +15,11 @@
(expect friday-the-13th (->Timestamp (.getTime friday-the-13th)))
(expect friday-the-13th (->Timestamp "2015-11-13T19:05:55+00:00"))
(expect nil (->ISO8601DateTime nil nil))
(expect "2015-11-13T19:05:55.000Z" (->ISO8601DateTime friday-the-13th nil))
(expect "2015-11-13T11:05:55.000-08:00" (->ISO8601DateTime friday-the-13th "US/Pacific"))
(expect "2015-11-14T04:05:55.000+09:00" (->ISO8601DateTime friday-the-13th "Asia/Tokyo"))
(expect 5 (date-extract :minute-of-hour friday-the-13th))
(expect 19 (date-extract :hour-of-day friday-the-13th))
(expect 6 (date-extract :day-of-week friday-the-13th))
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment