How to Convert A Clojure/Java Date to Simpler Form

后端 未结 2 468
面向向阳花
面向向阳花 2021-01-01 22:32

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

相关标签:
2条回答
  • 2021-01-01 22:42
    (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?.

    0 讨论(0)
  • 2021-01-01 22:43

    .parse takes a string in the format specified in the SimpleDateFormat constructor and turns it into a Date object. If you can just pass in the date, then use .format passing it the date to be formatted. If you need to pass in a string, then you'll need 2 SimpleDateFormats. One for the input format and one for the output format. Call .parse using the input format and .format using the output format.

    0 讨论(0)
提交回复
热议问题