How does implementing Time Ago look like Clojure?

I mean a function when a given time returns the smallest unit time back. For example,

  • "5 minutes ago"
  • 30 seconds ago
  • "just now"
+4
source share
3 answers

One possible implementation might look like this:

Note. I used the clj-time / clj-time ยท GitHub library .

(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 nil :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")))))))

Usage example:

(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"
+5
source

If you use Clojure in the JVM, consider using the PrettyTime library . Using this library to implement the "time back" in Java has been proposed here .

PrettyTime Clojure, :dependencies project.clj:

[org.ocpsoft.prettytime/prettytime "3.2.7.Final"]

Java interop. , " " 1 . , . , , , . " " " ". , .

(import 'org.ocpsoft.prettytime.PrettyTime
       'org.ocpsoft.prettytime.units.JustNow
       'java.util.Date)

(defn time-ago [date]
  (let [pretty-time (PrettyTime.)]
    (.. pretty-time (getUnit JustNow) (setMaxQuantity 1000))
    (.format pretty-time date)))

(let [now (System/currentTimeMillis)]
  (doseq [offset [200, (* 30 1000), (* 5 60 1000)]]
     (println (time-ago (Date. (- now offset))))))

;; moments ago
;; 30 seconds ago
;; 5 minutes ago
+3

Source: https://habr.com/ru/post/1606864/


All Articles