murtaza52
murtaza52

Reputation: 47441

how to parse a date into clj-time by ignoring the time and secs

Given the following string, I would like to get a date-time with only the date -

String "2013-02-20T17:24:33Z", I would like to get a date while ignoring the time and secs.

The following would work - (parse (formatters :date-time-no-ms) "2013-02-2T17:24:33Z"). However the resulting date-time object also contains the secs, how do I trim it down to just year-month-day ?

One way is do a regex and extract the required details and then parse it into a date - (clojure.core/re-find #"\d{4}-\d{2}-\d{1,2}" "2013-02-20T17:24:33Z") (parse (formatters :date) "2013-02-20")

However there should be a better way to the above by just using clj-time ?

Upvotes: 0

Views: 1395

Answers (3)

Aaron Blenkush
Aaron Blenkush

Reputation: 3059

Use the DateTime method .withTimeAtStartOfDay:

(let [^DateTime dt (parse (formatters :date-time-no-ms) "2013-02-2T17:24:33Z")]
  (.withTimeAtStartOfDay dt))

Note that the type hint ^DateTime increases the performance significantly.

Upvotes: 0

Hendekagon
Hendekagon

Reputation: 4643

(defn floor [dt f] 
  (apply date-time 
    (map #(%1 dt) 
      (take-while (partial not= f) [year month day hour minute sec milli]))))

(floor (parse (formatters :date-time-no-ms) "2013-02-2T17:24:33Z") hour)

Upvotes: 1

Vladimir Matveev
Vladimir Matveev

Reputation: 127751

clj-time is just a wrapper around Joda Time, so you can call methods on DateTime object directly, and fortunately there is a method DateTime#toDateMidnight():

user=> (parse (formatters :date-time-no-ms) "2013-02-2T17:24:33Z")
#<DateTime 2013-02-02T17:24:33.000Z>
user=> (.toDateMidnight (parse (formatters :date-time-no-ms) "2013-02-2T17:24:33Z"))
#<DateMidnight 2013-02-02T00:00:00.000Z>

Upvotes: 4

Related Questions