Time Formatting Parsing in Clojure
Clojure supports time formatting and parsing via pattern-based layouts.
(ns time-formatting-parsing
(:require [clj-time.core :as t]
[clj-time.format :as f]))
(defn main []
(let [now (t/now)]
; Here's a basic example of formatting a time
; according to ISO8601, which is similar to RFC3339
(println (f/unparse (f/formatters :date-time) now))
; Time parsing uses the same format as unparse
(let [t1 (f/parse (f/formatters :date-time) "2012-11-01T22:08:41.000Z")]
(println t1))
; Custom formatting
(println (f/unparse (f/formatter "h:mmaa") now))
(println (f/unparse (f/formatter "EEE MMM d HH:mm:ss yyyy") now))
(println (f/unparse (f/formatter "yyyy-MM-dd'T'HH:mm:ss.SSSZ") now))
; Custom parsing
(let [form (f/formatter "h mmaa")
t2 (f/parse form "8 41PM")]
(println t2))
; For purely numeric representations you can also
; use standard string formatting with the extracted
; components of the time value.
(println (format "%d-%02d-%02dT%02d:%02d:%02d-00:00"
(t/year now) (t/month now) (t/day now)
(t/hour now) (t/minute now) (t/second now)))
; parse will throw an exception on malformed input
(try
(f/parse (f/formatter "EEE MMM d HH:mm:ss yyyy") "8:41PM")
(catch Exception e
(println (.getMessage e))))))
(main)
In this Clojure version:
We use the
clj-time
library, which is based on Joda Time, for time operations.The
formatters
function fromclj-time.format
provides predefined formatters similar to Go’s time constants.Custom formats are created using the
formatter
function, which accepts a string pattern.The
unparse
function is used for formatting, whileparse
is used for parsing.Clojure’s
try
/catch
is used to handle parsing errors, similar to checking for errors in Go.The numeric formatting is done using Clojure’s
format
function, which is similar toprintf
in other languages.
When you run this program, you’ll see output similar to:
2023-06-15T12:34:56.789Z
2012-11-01T22:08:41.000Z
12:34PM
Thu Jun 15 12:34:56 2023
2023-06-15T12:34:56.789+0000
0000-01-01T20:41:00.000Z
2023-06-15T12:34:56-00:00
Invalid format: "8:41PM" is malformed at "8:41PM"
Note that the exact output will depend on the current time when you run the program. The Clojure version provides equivalent functionality to the original example, demonstrating time formatting and parsing in Clojure.