-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathformat.clj
More file actions
55 lines (46 loc) · 1.77 KB
/
format.clj
File metadata and controls
55 lines (46 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
(ns java-time.format
(:refer-clojure :exclude (format))
(:require [clojure.string :as string]
[java-time.core :as jt.c]
[java-time.util :as jt.u])
(:import [java.time.temporal TemporalAccessor]
[java.time.format DateTimeFormatter DateTimeFormatterBuilder ResolverStyle]))
(def predefined-formatters
(->> (jt.u/get-static-fields-of-type DateTimeFormatter DateTimeFormatter)
(jt.u/map-kv
(fn [^String n fmt]
[(string/lower-case (.replace n \_ \-)) fmt]))))
(defn- get-resolver-style [s]
(if (instance? ResolverStyle s) s
(case s
:strict ResolverStyle/STRICT
:smart ResolverStyle/SMART
:lenient ResolverStyle/LENIENT)))
(defn ^DateTimeFormatter formatter
"Constructs a DateTimeFormatter out of a
* format string - \"YYYY/mm/DD\", \"YYY HH:MM\", etc.
* formatter name - :date, :time-no-millis, etc.
Accepts a map of options as an optional second argument:
* `resolver-style` - either `:strict`, `:smart `or `:lenient`"
([fmt]
(formatter fmt {}))
([fmt {:keys [resolver-style]}]
(let [^DateTimeFormatter fmt
(cond (instance? DateTimeFormatter fmt) fmt
(string? fmt) (DateTimeFormatter/ofPattern fmt)
:else (get predefined-formatters (name fmt)))
fmt (if resolver-style
(.withResolverStyle fmt (get-resolver-style resolver-style))
fmt)]
fmt)))
(defn format
"Formats the given time entity as a string.
Accepts something that can be converted to a `DateTimeFormatter` as a first
argument. Given one argument uses the default format."
([o] (str o))
([fmt o]
(.format (formatter fmt) o)))
(defn ^TemporalAccessor parse
([fmt o] (parse fmt o {}))
([fmt o opts]
(.parse (formatter fmt opts) o)))