Search code examples
clojureclj-time

Clojure clj-time : parse local string


I have trouble making the interop between java.util.Date and clj-time.

I have first raw data which is an instance of java.util.Date, let's day :

(def date (new java.util.util.Date))

I want to turn in into a clj-time object so I do :

(def st-date (.toString date))

Output :

"Mon Mar 21 16:39:23 CET 2016"

I define a formatter

(def date-formatter (tif/formatter "EEE MMM dd HH:mm:ss zzz yyyy"))

All is here I think.

I so try

(tif/parse order-date-formatter st-date)

I have an exception which tell me the format is not right.

I tried

(tif/unparse order-date-formatter (tic/now))

And I have

"lun. mars 21 15:50:29 UTC 2016"

Which is the same datetime as the java String but in French (my language) with UTC

Wrapping the code for test

(defn today-date-to-clj []
  (let [st-date (.toString (new java.util.util.Date))
        date-formatter (tif/formatter "EEE MMM dd HH:mm:ss zzz yyyy")]
    (tif/parse date-formatter st-date)))

I seems that the formatter does not work on the string because it's not the same localization, am I right ? How to change it ?

Thanks for the help !

EDIT

Someone gave me a far better answer but this almost worked for curious people (problem at "CET 2016" but works for unparse)

(def uni-formatter (tif/with-locale (tif/with-zone order-date-formatter (DateTimeZone/forID "Europe/Paris")) java.util.Locale/US))

Solution

  • Instead of using String as an intermediate date representation you should use a direct conversion:

    (clj-time.coerce/from-date (java.util.Date.))