迭代Joda Time的间隔

时间:2012-08-19 21:53:43

标签: java clojure

是否可以在间隔的开始和结束日期之间迭代一次,一次一天?使用clj-time库进行Clojure也没关系!

4 个答案:

答案 0 :(得分:13)

是的。

这样的事情:

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);
}

此外,这是Clojure的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])))))

答案 1 :(得分:8)

这应该有用。

(take-while (fn [t] (cljt/before? t to)) (iterate (fn [t] (cljt/plus t period)) from))

答案 2 :(得分:2)

使用clj-time,-interval是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))))))

答案 3 :(得分:1)

Clj-time具有periodic-seq功能。它看起来非常像Hendekagon的解决方案。这可以与开始/结束函数结合使用,以创建类似:

的内容
(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 ))))