-
Notifications
You must be signed in to change notification settings - Fork 1
/
time.cljc
35 lines (32 loc) · 1.09 KB
/
time.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
(ns com.yetanalytics.persephone.utils.time
"Functions for date and time."
(:require #?(:clj [clojure.instant :as instant]
:cljs [cljs.reader :as cljs-reader])))
(defn parse-timestamp
"Parse the ISO 8601 timestamp `s`."
[s]
(try
#?(:clj (instant/read-instant-date s)
:cljs (cljs-reader/parse-timestamp s))
(catch #?(:clj Exception :cljs js/Error) _
(let [msg (if (nil? s)
"Cannot parse nil or missing timestamp string!"
(str "Cannot parse timestamp: " s))]
(throw (ex-info msg {:kind ::parse-failure :timestamp s}))))))
(defn compare-timestamps*
"Same as `compare-timestamps` but assumes `t1` and `t2` are
already parsed."
[t1 t2]
#?(:clj
(.compareTo t1 t2)
:cljs
(cond
(= t1 t2) 0
(< t1 t2) -1
:else 1)))
(defn compare-timestamps
"Returns a negative number if `t1` occurs before `t2`, a positive
number if `t1` occurs after `t2`, and 0 otherwise. `t1` and `t2`
must be ISO 8601 timestamp strings."
[t1 t2]
(compare-timestamps* (parse-timestamp t1) (parse-timestamp t2)))