Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert A Clojure/Java Date to Simpler Form

Tags:

date

clojure

I want to take

(str (Date.))
"Thu Feb 07 12:15:03 EST 2013"

and turn it into a string, so it can be input into an Informix date field mm/dd/yyyy.

02/07/2013

I have been looking at various posts, with no success. Here's the first thing I found, and tried, knowing I'd have to reverse the order of the date format. I just wanted to get it to work.

(defn str-to-date [date] (. (SimpleDateFormat. "yyyy-MM-dd") parse date))

I get this error

(str-to-date (str (Date.)))
ParseException Unparseable date: 
"Thu Feb 07 12:44:41 EST 2013"  java.text.DateFormat.parse (DateFormat.java:354)

I have also tried this

 (.parse (SimpleDateFormat. "mm/DD/yyyy") (str (Date.)))
ParseException Unparseable date: 
"Thu Feb 07 12:42:02 EST 2013"  java.text.DateFormat.parse (DateFormat.java:354)

with no success. Any documentation pointers or answers would be appreciated.

like image 374
octopusgrabbus Avatar asked Feb 07 '13 17:02

octopusgrabbus


1 Answers

(def date (java.util.Date.))
date 
=> #inst "2013-02-07T19:08:12.107-00:00"

You can directly format to desired format

(.format (java.text.SimpleDateFormat. "MM/dd/yyyy") date)
=> "02/07/2013"

But if starting from a string,

(str date)
=> "Thu Feb 07 13:08:12 CST 2013"

you must first parse using that string's format

(def df (java.text.SimpleDateFormat. "EEE MMM d HH:mm:ss zzz yyyy"))
(.parse df (str date))
=> #inst "2013-02-07T19:08:12.107-00:00"

and then back to the desired format

(.format (java.text.SimpleDateFormat. "MM/dd/yyyy") (.parse df (str date)))
=> "02/07/2013"

You might also want to look into some time and date libraries: What are the Clojure time and date libraries?.

like image 112
A. Webb Avatar answered Oct 04 '22 14:10

A. Webb