DigressEd.net
Ocasional Digressions
Dates with babashka
I seldomly do date/time manipulation with babashka and, while working on a recent personal project, I had to look it all up and it took much longer than it should. Ergo, for future reference:
- Imports:
(ns mybb (:import (java.time Instant Duration ZonedDateTime ZoneId) (java.time.format DateTimeFormatter)))
- Common defs:
(def now (Instant/now)) (def zone-id (ZoneId/systemDefault)) ; => #object[java.time.ZoneRegion 0x71cb68be "Europe/Paris"] (def local-date-pattern (DateTimeFormatter/ofPattern "dd/MM/yyyy")) (def tz-datetime-pattern (DateTimeFormatter/ofPattern "dd/MM/yyyy HH:mm:ss z"))
- Formatting a date instance as a string:
(.format local-date-pattern date)
- Get the system zone-id and determine the time-offset.
(def tz-offset (.getOffset (.getRules zone-id) now)) ; => #object[java.time.ZoneOffset 0x57d84226 "+02:00"] (.toString tz-offset) ; => "+02:00"
- Parse a date to create a
ZonedDateTime
.(ZonedDateTime/parse "09/11/2023 12:01:04 +02:00" tz-datetime-pattern) ; => #object[java.time.ZonedDateTime 0x70411fb8 "2023-11-09T12:01:04+02:00"]
- date +/- number of days
(.minusDays zoned-datetime 10) (.plusDays zoned-datetime 10)
- Difference between two date-times, in seconds. NOTE: to convert to instants, you must be using
ZonedDateTime
.(-> (Duration/between (.toInstant zoned-datetime-1) (.toInstant zoned-datetime-2)) (.getSeconds))
Published: 2024-08-19