Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for js/Date in datetime #41

Merged
merged 2 commits into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/clj_commons/humanize/time_convert.cljc
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
#_:clj-kondo/ignore
(ns ^:no-doc clj-commons.humanize.time-convert
"Internal utility to convert strings and other typs into LocalDateTime "
(:require [cljc.java-time.extn.predicates :as jt.predicates]
[cljc.java-time.format.date-time-formatter :as dt.formats]
[cljc.java-time.local-date-time :as jt.ldt]
[cljc.java-time.instant :as jt.i]
[cljc.java-time.zone-id :as jt.zi]
#?(:clj [clj-commons.humanize.time-convert.jvm :as jvm])))

(defn- looks-like-an-iso8601-string?
Expand All @@ -21,18 +24,21 @@
- java.time.LocalDateTime and java.time.LocalDate
- java.util.Date (on the JVM)
- Strings in 'yyyy-MM-dd' and 'yyyy-MM-ddTHH:MM:SS' formats
- js/Date

Throws an Exception if unable to convert."
[t]
(cond
;; t is already a java.time.LocalDateTime
(jt.predicates/local-date-time? t) t

#?@(:clj [(jt.predicates/local-date? t)
(jt.ldt/parse (jvm/java-time-local-date->iso8601-str t) dt.formats/iso-date-time)
#?@(:clj [(jt.predicates/local-date? t)
(jt.ldt/parse (jvm/java-time-local-date->iso8601-str t) dt.formats/iso-date-time)

(jvm/java-util-date? t)
(jt.ldt/parse (jvm/java-util-date->iso8601-str t) dt.formats/iso-date-time)])
(jvm/java-util-date? t)
(jt.ldt/parse (jvm/java-util-date->iso8601-str t) dt.formats/iso-date-time)]
:cljs [(instance? js/Date t)
(jt.ldt/of-instant (jt.i/of-epoch-milli (.getTime t)) (jt.zi/system-default))])

;; Strings
(looks-like-an-iso8601-string? t)
Expand Down
6 changes: 6 additions & 0 deletions test/clj_commons/humanize_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,12 @@
(is (= "10 minutes ago"
(datetime (jt.ldt/now)
:now-dt (jt.ldt/plus-minutes (jt.ldt/now) 10)))))
#?@(:cljs
(testing "datetime accepts js/Date"
(is (= "a moment ago" (datetime (js/Date.))))
(is (= "10 minutes ago"
(datetime (js/Date.)
:now-dt (jt.ldt/plus-minutes (jt.ldt/now) 10))))))
(testing "test phrases"
(doseq [[phrase time-shift-fn] datetime-test-phrases]
(is (= phrase
Expand Down