Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating Joda Time's Interval

Tags:

java

clojure

Is it possible to iterate the time between an interval's beginning and ending date, one day at a time? Using the clj-time library for Clojure would be fine as well!

like image 867
Mike Avatar asked Aug 19 '12 21:08

Mike


4 Answers

Yep.

Something like this:

DateTime now = DateTime.now();
DateTime start = now;
DateTime stop = now.plusDays(10);
DateTime inter = start;
// Loop through each day in the span
while (inter.compareTo(stop) < 0) {
    System.out.println(inter);
    // Go to next
    inter = inter.plusDays(1);
}

Additionally, here's the implementation for Clojure's clj-time:

(defn date-interval
  ([start end] (date-interval start end []))
  ([start end interval]
   (if (time/after? start end)
     interval
     (recur (time/plus start (time/days 1)) end (concat interval [start])))))
like image 145
Oskar Kjellin Avatar answered Nov 14 '22 10:11

Oskar Kjellin


This should work.

(take-while (fn [t] (cljt/before? t to)) (iterate (fn [t] (cljt/plus t period)) from))
like image 8
Hendekagon Avatar answered Nov 14 '22 12:11

Hendekagon


Using clj-time, the-interval is a Joda Interval :

(use '[clj-time.core :only (days plus start in-days)])
(defn each-day [the-interval f]
 (let [days-diff (in-days the-interval)]
    (for [x (range 0 (inc days-diff))] (f (plus (start the-interval) (days x))))))
like image 2
DanLebrero Avatar answered Nov 14 '22 10:11

DanLebrero


Clj-time has the periodic-seq function. It looks very much like Hendekagon's solution. That could be combined with the begin/end functions to create something like:

(defn interval-seq 
  "Returns sequence of period over interval. 
   For example, the individual days in an interval using (clj-time.core/days 1) as the period."
  [interval period]
  (let [end (clj-time.core/end interval)]
      (take-while #(clj-time.core/before? % end) (clj-time.periodic/periodic-seq  (clj-time.core/start interval) period ))))
like image 1
robbie.huffman Avatar answered Nov 14 '22 11:11

robbie.huffman