Reputation: 139
I want to use two variables, dateFrom and dateTo. the script in which they exist will be run automatically by a job scheduler. I want the two variables to be updated automatically so that they can be passed to a DB query and are always pulling back the data from the previous day.
Therefore, if today is the 13th of September, dateFrom should contain bthe 11th of september and dateTo should contain the 12th of september.
Every time the script is run, the variables should be automatically updated. The format for the date should be YYYYMMDD
Does anyone know if this can be done in Clojure?
Many thanks for your help
Upvotes: 1
Views: 648
Reputation: 7825
You can use clj-time
for this:
(use '[clj-time.core :only [days minus today]]
'[clj-time.coerce :only [to-sql-date]])
(let [start (-> (today) (minus (days 2)) to-sql-date)
end (-> (today) (minus (days 1)) to-sql-date)]
[start end])
Upvotes: 3
Reputation: 6681
Here's an example session from the Clojure REPL with the required operations:
user=> (import java.util.Date)
java.util.Date
user=> (def now (Date.))
#'user/now
user=> (import java.util.Calendar)
java.util.Calendar
user=> (def cal (Calendar/getInstance))
#'user/cal
user=> (.setTime cal now)
nil
user=> (.add cal Calendar/DATE -2)
nil
user=> (def dateFrom (.getTime cal))
#'user/dateFrom
user=> (.setTime cal now)
nil
user=> (.add cal Calendar/DATE -1)
nil
user=> (def dateTo (.getTime cal))
#'user/dateTo
user=> (import java.text.SimpleDateFormat)
java.text.SimpleDateFormat
user=> (def sdf (SimpleDateFormat. "yyyyMMdd"))
#'user/sdf
user=> (.format sdf dateFrom)
"20130912"
user=> (.format sdf dateTo)
"20130913"
Upvotes: 1