Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure - parse string to date

I'm trying to parse a unformatted string which contains a date (e.g. today = "08082013") to the format "08.08.2013".

This works: (.parse (java.text.SimpleDateFormat. "ddMMyyyy") today) => <Date Sun Jan 01 00:00:00 CET 1950>

But when I do (.parse (java.text.SimpleDateFormat. "dd.MM.yyyy") today) I get the error "Unparseable date: "08082013"

Why? How can I get my desired date format?

like image 322
m-arv Avatar asked Aug 08 '13 11:08

m-arv


2 Answers

To get from string to date, use parse.

To get from date to string, use format.

Both use a formatter to describe the transition.

=>(.format
    (java.text.SimpleDateFormat. "dd.MM.yyyy")
    (.parse
      (java.text.SimpleDateFormat. "ddMMyyyy")
      "08082013"))

"08.08.2013"
like image 197
NielsK Avatar answered Sep 22 '22 03:09

NielsK


If you are playing around with date and time I recommend checking out this Clojure lib,

https://github.com/clj-time/clj-time

It is kind of the time lib most Clojure programmers use, and is based on the java lib joda time, that by many is agreed to be better than the Java build in one.

like image 29
pjc Avatar answered Sep 24 '22 03:09

pjc