Database Reference
In-Depth Information
2.
Notice that some of these are keywords and some are strings. Each needs to be
handled differently. We'll deine a protocol with the method ->formatter , which
attempts to convert each type to a date formatter, and the protocol for both the
types to be represented in the format list:
(defprotocol ToFormatter
(->formatter [fmt]))
(extend-protocol ToFormatter
java.lang.String
(->formatter [fmt]
(formatter fmt))
clojure.lang.Keyword
(->formatter [fmt] (formatters fmt)))
3.
Next, parse-or-nil will take a format and a date string, attempt to parse the
date string, and return nil if there are any errors:
(defn parse-or-nil [fmt date-str]
(try
(parse (->formatter fmt) date-str)
(catch Exception ex
nil)))
4.
With these in place, here is normalize-datetime . We just attempt to parse
a date string with all of the formats, ilter out any nil values, and return the irst
non-nil. Because Clojure's lists are lazy, this will stop processing as soon as one
format succeeds:
(defn normalize-datetime [date-str]
(first
(remove nil?
(map #(parse-or-nil % date-str)
*default-formats*))))
Now we can try this out:
user=> (normalize-datetime "2012-09-12")
#<DateTime 2012-09-12T00:00:00.000Z>
user=> (normalize-datetime "2012/09/12")
#<DateTime 2012-09-12T00:00:00.000Z>
user=> (normalize-datetime "28 Sep 2012")
#<DateTime 2012-09-28T00:00:00.000Z>
user=> (normalize-datetime "2012-09-28 13:45")
#<DateTime 2012-09-28T13:45:00.000Z>
 
Search WWH ::




Custom Search