迭代Joda Time的间隔

Mik*_*ike 7 java clojure

是否有可能在间隔的开始和结束日期之间迭代时间,一次一天?使用clj-timeClojure库也可以!

Osk*_*lin 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);
}
Run Code Online (Sandbox Code Playgroud)

另外,这是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])))))
Run Code Online (Sandbox Code Playgroud)

  • 我知道这只是演示代码,但请注意,您应该避免在同一函数中调用DateTime.now()两次,因为它会导致意外.now()第二次与第一次不同的now().如果你跑过午夜的边界并且采取每个的日期或类似的东西,这可能会导致令人讨厌的小鬼,所以这是一个坏习惯.创建一个本地"now"变量来代替算术. (2认同)

Hen*_*gon 8

这应该工作.

(take-while (fn [t] (cljt/before? t to)) (iterate (fn [t] (cljt/plus t period)) from))
Run Code Online (Sandbox Code Playgroud)