Time Ago功能实现在Clojure中会如何?

时间:2015-09-10 20:53:47

标签: clojure clojurescript

我的意思是功能,当给定时间返回最小时间单位之前。 E.g

  • " 5分钟前"
  • " 30秒前"
  • "刚才"

1 个答案:

答案 0 :(得分:5)

一种可能的实现可能如下所示:

注意,我已使用clj-time/clj-time · GitHub库。

(require '[clj-time.core :as t])

(defn time-ago [time]
  (let [units [{:name "second" :limit 60 :in-second 1}
               {:name "minute" :limit 3600 :in-second 60}
               {:name "hour" :limit 86400 :in-second 3600}
               {:name "day" :limit 604800 :in-second 86400}
               {:name "week" :limit 2629743 :in-second 604800}
               {:name "month" :limit 31556926 :in-second 2629743}
               {:name "year" :limit Long/MAX_VALUE :in-second 31556926}]
        diff (t/in-seconds (t/interval time (t/now)))]
    (if (< diff 5)
      "just now"
      (let [unit (first (drop-while #(or (>= diff (:limit %))
                                         (not (:limit %))) 
                                    units))]
        (-> (/ diff (:in-second unit))
            Math/floor
            int
            (#(str % " " (:name unit) (when (> % 1) "s") " ago")))))))

使用示例:

(time-ago (t/minus (t/now) (t/days 400)))
=> "1 year ago"

(time-ago (t/minus (t/now) (t/days 15)))
=> "2 weeks ago"

(time-ago (t/minus (t/now) (t/seconds 45))) 
=> "45 seconds ago"

(time-ago (t/minus (t/now) (t/seconds 1)))
=> "just now"