gpt4 book ai didi

clojure - Time Ago 函数在 Clojure 中的实现是什么样的?

转载 作者:行者123 更新时间:2023-12-02 11:14:37 26 4
gpt4 key购买 nike

我的意思是函数,当给定时间返回最小时间单位之前。例如

  • “5分钟前”
  • “30 秒前”
  • “刚才”

最佳答案

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

注意,我用过 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"

关于clojure - Time Ago 函数在 Clojure 中的实现是什么样的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32511405/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com