Jyd
Jyd

Reputation: 227

Convert non-integer number to day in clojure

I have a function that basically takes in a date string and number of days to add to the given date string

(defn add-period [date-string d]
  (t/plus (tf/parse (tf/formatter "yyyy-MM-dd") date-string) (t/days d)))

and we call the function thus

(add-period "2014-05-12" 7)
;=>  #object[org.joda.time.DateTime 0x2002348 2014-05-19T00:00:00.000Z]


(add-period "2014-05-12" -7)
;=>  #object[org.joda.time.DateTime 0x2002348 2014-05-5T00:00:00.000Z]


(add-period "2014-05-12" 365)
;=>  #object[org.joda.time.DateTime 0x2002348 2015-05-5T00:00:00.000Z]

But I also want to do this:

(add-period "2014-05-12" 0.5)

0.5 will add half a day, and 0.956 will add (57minutes 36 seconds)

I'd appreciate if the function is refactored to accommodate this use cases

I think an issue was raised about this:

t/days doc misleading or bug?

Upvotes: 0

Views: 162

Answers (1)

cfrick
cfrick

Reputation: 37008

You can use milliseconds. E.g.:

$ lein try clj-time 0.11.0
...
user=> (require '[clj-time.core :as t])
nil
user=> (import 'org.joda.time.DateTimeConstants)
org.joda.time.DateTimeConstants
user=> (t/plus (t/date-time 2015 8 21) (t/millis (* 0.5 (DateTimeConstants/MILLIS_PER_DAY))))
#<DateTime 2015-08-21T12:00:00.000Z>
user=> (t/plus (t/date-time 2015 8 21) (t/millis (* 0.956 (DateTimeConstants/MILLIS_PER_DAY))))
#<DateTime 2015-08-21T22:56:38.400Z>

Upvotes: 2

Related Questions