花费时间和Java时间/迭代创建奇怪的结果

时间:2019-03-03 14:58:02

标签: clojure java-time

我正在使用clojure.java-time版本0.3.2,并且我定义了一个TemporalAdjuster,如下所示:

(def next-pay-day
  (reify java.time.temporal.TemporalAdjuster
    (adjustInto [this temporal]
      (let [local-date (java.time.LocalDate/from temporal)
            day-of-month (j/as local-date :day-of-month)
            last-day-of-month (j/as (j/adjust local-date :last-day-of-month) :day-of-month)]
        (cond 
          (= day-of-month last-day-of-month) 
          (j/plus local-date (j/days 14))

          (< day-of-month 14) 
          (j/plus local-date (j/days (- 14 day-of-month)))

          :else 
          (j/adjust local-date :last-day-of-month))))))

哪个工作是这样的

=> (require '[pto-calculator.logic.pay-periods :as p])
nil
=> (require '[java-time :as j])
nil
=> (take 4 (j/iterate j/adjust (j/local-date 2019 3 3) p/next-pay-day))
(#object[java.time.LocalDate 0x74e53020 "2019-03-03"] #object[java.time.LocalDate 0x49980a "2019-03-14"] #object[java.time.LocalDate 0x2e332a36 "2019-03-31"] #object[java.time.LocalDate 0x5e7aaec6 "2019-04-14"])

我正在尝试生成从今天到t之间的发薪日列表,其中t是将来的LocalDate。我有这个,但问题是它似乎在某些日期(4月15日)有效:

=> (take-while #(= 1 (compare (j/local-date 2019 4 15) %)) (j/iterate j/adjust (j/local-date 2019 3 3) p/next-pay-period))
(#object[java.time.LocalDate 0xc994eb6 "2019-03-03"] #object[java.time.LocalDate 0x3ec8e48 "2019-03-14"] #object[java.time.LocalDate 0x1bddd9d5 "2019-03-31"] #object[java.time.LocalDate 0x133ed931 "2019-04-14"])
; Last date is 2019-04-14 (expected)

但不适用于其他人(4月18日):

=> (take-while #(= 1 (compare (j/local-date 2019 4 18) %)) (j/iterate j/adjust (j/local-date 2019 3 3) p/next-pay-period))
(#object[java.time.LocalDate 0x7f0ac64b "2019-03-03"] #object[java.time.LocalDate 0x1f1d3684 "2019-03-14"] #object[java.time.LocalDate 0x70415bc3 "2019-03-31"])
; Last date is 2019-03-31 (unexpected, should be 2019-04-14)

为什么该操作在4月18日缩短,但在4月15日却能正常工作?

1 个答案:

答案 0 :(得分:6)

compare并不总是返回1、0或-1。因此,代替:

#(= 1 (compare (j/local-date 2019 4 15) %))

尝试:

#(pos? (compare (j/local-date 2019 4 15) %))