Epoch in Clojure

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Clojure.

(ns epoch-example
  (:import (java.time Instant)))

(defn main []
  ;; Use Instant.now() to get the current time
  (let [now (Instant/now)]
    (println now)

    ;; Get elapsed time since the Unix epoch in seconds,
    ;; milliseconds or nanoseconds
    (println (.getEpochSecond now))
    (println (.toEpochMilli now))
    (println (.getNano now))

    ;; You can also convert integer seconds or nanoseconds
    ;; since the epoch into the corresponding Instant
    (println (Instant/ofEpochSecond (.getEpochSecond now)))
    (println (Instant/ofEpochSecond 0 (.getNano now))))

  ;; Call the main function
  (main))

To run this Clojure program:

$ clj epoch.clj
2023-05-29T12:34:56.789012Z
1685363696
1685363696789
789012000
2023-05-29T12:34:56Z
1970-01-01T00:00:00.789012Z

In this Clojure version:

  1. We use java.time.Instant to work with time, which is similar to Go’s time.Time.
  2. Instant/now is used to get the current time, equivalent to time.Now() in Go.
  3. We use .getEpochSecond, .toEpochMilli, and .getNano methods to get the time in different units.
  4. Instant/ofEpochSecond is used to create an Instant from seconds or nanoseconds, similar to time.Unix in Go.

Note that Clojure, being a JVM language, uses Java’s time utilities. The concepts are similar, but the syntax and exact method names differ from Go.

Next, we’ll look at another time-related task: time parsing and formatting.