Clojure: Converting a string to a date
Join the DZone community and get the full member experience.
Join For FreeI wanted to do some date manipulation in Clojure recently and figured that since clj-time is a wrapper around Joda Time it’d probably do the trick.
The first thing we need to do is add the dependency to our project file and then run lein reps to pull down the appropriate JARs. The project file should look something like this:
project.clj
(defproject ranking-algorithms "0.1.0-SNAPSHOT" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.4.0"] [clj-time "0.6.0"]])
Now let’s load the clj-time.format namespace into the REPL since we know we’ll be parsing dates:
> (require '(clj-time [format :as f]))
The string that I want to convert into a date looks like this:
(def string-date "18 September 2012")
The first thing we should do is check whether there is an existing formatter that we can use by evaluating the following function:
> (f/show-formatters) ... :hour-minute 06:45 :hour-minute-second 06:45:22 :hour-minute-second-fraction 06:45:22.473 :hour-minute-second-ms 06:45:22.473 :mysql 2013-09-20 06:45:22 :ordinal-date 2013-263 :ordinal-date-time 2013-263T06:45:22.473Z :ordinal-date-time-no-ms 2013-263T06:45:22Z :rfc822 Fri, 20 Sep 2013 06:45:22 +0000 ...
There are a lot of different built in formatters but unfortunately I couldn’t find one that exactly matched our date format so we’ll have to write our own one.
For that we’ll need to refresh our knowledge of Java date formatting:
We end up with the following formatter:
> (f/parse (f/formatter "dd MMM YYYY") string-date) #<DateTime 2012-09-18T00:00:00.000Z>
It took me much longer than it should have to remember that ‘MMM’ is the pattern to match a short form of a month but it’s just the same as what we’d have to do in Java but with some neat wrapper functions.
Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments