【问题标题】:Iterating Joda Time's Interval迭代 Joda Time 的时间间隔
【发布时间】:2012-08-15 08:24:10
【问题描述】:

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

【问题讨论】:

    标签: java clojure


    【解决方案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 ))))
    

    【讨论】:

      【解决方案2】:

      这应该可行。

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

      【讨论】:

      • 这是一个很好的解决方案,值得更多关注。值得注意的是,这样做是在间隔中创建一个延迟的日期时间序列。这是超级惯用的,可以用各种有用的东西组合,比如 (doseq [t (seq-generator...)])。唯一不同的可能是a)将它放在一个函数中,以便它返回seq,例如(定义时间序列 [...] ...)。在返回 fn 的时间序列中,您还希望将间隔解压缩到 to/from 而不是依赖全局变量。
      【解决方案3】:

      使用 clj-time,the-interval 是一个 Joda 间隔:

      (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))))))
      

      【讨论】:

        【解决方案4】:

        是的。

        类似这样的:

        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])))))
        

        【讨论】:

        • 希望避免编写命令式解决方案,但我想这就是我们所拥有的。制作一个 clj-time Clojure 解决方案,将立即与您的答案结合。
        • @Mike 将其修改为使用 joda-time。您可以创建一个返回 List&lt;DateTime&gt; 的方法
        • 谢谢。是的,我的初衷是在 API 中找到这个功能。无论如何谢谢!
        • @Mike 认为没有。可能有点取决于你想要它的目的。是否计时,时区等。
        • 我知道这只是演示代码,但请注意,您应该避免在同一个函数中调用 DateTime.now() 两次,因为它会导致意外。 now() 第二次与第一次不同 now() 。如果你跑过午夜边界并记录每个日期的日期,或者类似的东西,这可能会导致讨厌的小鬼,所以这是一个坏习惯。制作一个本地“现在”变量来代替你的算术。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多