Created
October 17, 2024 16:11
-
-
Save henryw374/38d61b20c62cd5450331f36ee9029a61 to your computer and use it in GitHub Desktop.
clojure java.time clock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns flexi-clock | |
(:import (java.time Clock Duration Instant ZonedDateTime))) | |
(defn clock | |
"potential library function (e.g. in tick or tempo). | |
This just implements the platform Clock - which works because non-test code only uses that API. | |
Any manipulation of time (which happens in testing code) is done via changing | |
what get-instant and get-zone return" | |
[get-instant get-zone] | |
(proxy [Clock] [] | |
(getZone [] (get-zone)) | |
(instant [] (get-instant)))) | |
(defn zdt-atom-clock | |
"a common use case - could also be in a library" | |
[zdt-atom] | |
(clock | |
(fn get-instant [] | |
(ZonedDateTime/.toInstant @zdt-atom)) | |
(fn get-zone [] | |
(ZonedDateTime/.getZone @zdt-atom)))) | |
(comment | |
;first create holder for the fixed zdt values | |
(def zdt-atom (atom (ZonedDateTime/parse "2024-10-17T01:00:00.000+00:00[UTC]"))) | |
;create the clock | |
(def c (zdt-atom-clock zdt-atom)) | |
; use the clock | |
(Instant/now c) | |
; change the fixed zdt however you want | |
(swap! zdt-atom (fn [zdt] (ZonedDateTime/.plusHours zdt 2))) | |
; see that 'now' is different | |
(Instant/now c) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment