|
| 1 | +;; Copyright (c) Rich Hickey. All rights reserved. |
| 2 | +;; The use and distribution terms for this software are covered by the |
| 3 | +;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) |
| 4 | +;; which can be found in the file epl-v10.html at the root of this distribution. |
| 5 | +;; By using this software in any fashion, you are agreeing to be bound by |
| 6 | +;; the terms of this license. |
| 7 | +;; You must not remove this notice, or any other, from this software. |
| 8 | + |
| 9 | +(ns cljs.instant |
| 10 | + (:require [clojure.instant :as inst]) |
| 11 | + (:import [java.time Instant OffsetDateTime ZoneOffset] |
| 12 | + [java.time.format DateTimeFormatter DateTimeFormatterBuilder] |
| 13 | + [java.util Locale Locale$Category])) |
| 14 | + |
| 15 | +(set! *warn-on-reflection* true) |
| 16 | + |
| 17 | +(def ^:private ^java.time.format.DateTimeFormatter utc-format |
| 18 | + (-> (DateTimeFormatterBuilder.) |
| 19 | + (.appendInstant 9) |
| 20 | + (.toFormatter (Locale/getDefault Locale$Category/FORMAT)))) |
| 21 | + |
| 22 | +(defn- remove-last-char ^String [s] |
| 23 | + (subs s 0 (dec (count s)))) |
| 24 | + |
| 25 | +(defn- print-instant |
| 26 | + "Print a java.time.Instant as RFC3339 timestamp, always in UTC." |
| 27 | + [^java.time.Instant instant, ^java.io.Writer w] |
| 28 | + (.write w "#inst \"") |
| 29 | + (.write w (remove-last-char (.format utc-format instant))) |
| 30 | + (.write w "-00:00\"")) |
| 31 | + |
| 32 | +(defmethod print-method java.time.Instant |
| 33 | + [^java.time.Instant instant, ^java.io.Writer w] |
| 34 | + (print-instant instant w)) |
| 35 | + |
| 36 | +(defmethod print-dup java.time.Instant |
| 37 | + [^java.time.Instant instant, ^java.io.Writer w] |
| 38 | + (print-instant instant w)) |
| 39 | + |
| 40 | +(defn- construct-instant |
| 41 | + "Construct a java.time.Instant, which has nanosecond precision." |
| 42 | + [years months days hours minutes seconds nanoseconds |
| 43 | + offset-sign offset-hours offset-minutes] |
| 44 | + (Instant/from |
| 45 | + (OffsetDateTime/of years months days hours minutes seconds nanoseconds |
| 46 | + (ZoneOffset/ofHoursMinutes (* offset-sign offset-hours) (* offset-sign offset-minutes))))) |
| 47 | + |
| 48 | +(defn read-instant-instant |
| 49 | + "To read an instant as a java.time.Instant, bind *data-readers* to a |
| 50 | + map with this var as the value for the 'inst key. Instant preserves |
| 51 | + fractional seconds with nanosecond precision. The timezone offset will |
| 52 | + be used to convert into UTC." |
| 53 | + [^CharSequence cs] |
| 54 | + (inst/parse-timestamp (inst/validated construct-instant) cs)) |
0 commit comments