5

In clojure I want to add days to current date can anyone please guide me on that. Am getting current date as below and now let's say I want to add 7 days to it, how can I get a new date?

(.format (java.text.SimpleDateFormat. "MM/dd/yyyy") (java.util.Date.))
Robin
  • 167
  • 1
  • 2
  • 8

2 Answers2

7

This would work:

(java.util.Date. (+ (* 7 86400 1000) (.getTime (java.util.Date.)))

I prefer to use System/currentTimeMillis for the current time:

(java.util.Date. (+ (* 7 86400 1000) (System/currentTimeMillis)))

Or you can use clj-time which is a nicer api to deal with time (it's a wrapper around Joda Time). From the readme file:

(t/plus (t/date-time 1986 10 14) (t/months 1) (t/weeks 3))

=> #<DateTime 1986-12-05T00:00:00.000Z>

Diego Basch
  • 12,764
  • 2
  • 29
  • 24
  • This is wrong! You should never assume that a day always has 86400 seconds in it. If you are crossing the boundary of DST you will be will be either getting an extra hour or losing an extra hour. – redfish64 Aug 01 '15 at 03:09
  • Ex: (.format (java.text.SimpleDateFormat. "yyyy/MM/dd HH:mm z") (java.util.Date. (+ (* 7 86400 1000) (.getTime (.parse (java.text.SimpleDateFormat. "yyyy/MM/dd HH:mm z") "2015/03/05 00:00 PDT"))))) produces "2015/03/11 23:00 GMT-08:00", not "2015/03/12 00:00 GMT -0:8:00" as desired. – redfish64 Aug 01 '15 at 03:19
1
user> (import '[java.util Calendar])
;=> java.util.Calendar
user> (defn days-later [n]
        (let [today (Calendar/getInstance)]
          (doto today
            (.add Calendar/DATE n)
            .toString)))
#'user/days-later
user> (println "Tomorrow: " (days-later 1))
;=> Tomorrow:  #inst "2014-11-26T15:36:31.901+09:00"
;=> nil
user> (println "7 Days from now: " (days-later 7))
;=> 7 Days from now:  #inst "2014-12-02T15:36:44.785+09:00"
;=> nil
runexec
  • 862
  • 4
  • 8