2016-05-20 11:20:48 +00:00
|
|
|
(ns status-im.utils.datetime
|
2016-05-20 09:41:55 +00:00
|
|
|
(:require [cljs-time.core :as t :refer [date-time now plus days hours before?]]
|
|
|
|
[cljs-time.coerce :refer [from-long to-long]]
|
2016-08-04 15:36:13 +00:00
|
|
|
[cljs-time.format :refer [formatters
|
|
|
|
formatter
|
|
|
|
unparse]]
|
2016-06-30 16:00:44 +00:00
|
|
|
[status-im.i18n :refer [label label-pluralize]]
|
|
|
|
[goog.string :as gstring]
|
|
|
|
goog.string.format))
|
2016-08-04 15:36:13 +00:00
|
|
|
|
|
|
|
(def hour (* 1000 60 60))
|
|
|
|
(def day (* hour 24))
|
|
|
|
(def week (* 7 day))
|
2016-06-30 16:00:44 +00:00
|
|
|
(def units [{:name :t/datetime-second :limit 60 :in-second 1}
|
|
|
|
{:name :t/datetime-minute :limit 3600 :in-second 60}
|
|
|
|
{:name :t/datetime-hour :limit 86400 :in-second 3600}
|
|
|
|
{:name :t/datetime-day :limit nil :in-second 86400}])
|
2016-05-20 09:41:55 +00:00
|
|
|
|
|
|
|
(def time-zone-offset (hours (- (/ (.getTimezoneOffset (js/Date.)) 60))))
|
|
|
|
|
2016-10-04 20:58:33 +00:00
|
|
|
(defn to-short-str
|
|
|
|
([ms]
|
|
|
|
(to-short-str ms #(unparse (formatters :hour-minute) %)))
|
|
|
|
([ms today-format-fn]
|
|
|
|
(let [date (from-long ms)
|
|
|
|
local (plus date time-zone-offset)
|
|
|
|
today-date (t/today)
|
|
|
|
today (date-time (t/year today-date)
|
|
|
|
(t/month today-date)
|
|
|
|
(t/day today-date))
|
|
|
|
yesterday (plus today (days -1))]
|
|
|
|
(cond
|
|
|
|
(before? local yesterday) (unparse (formatter "dd MMM") local)
|
|
|
|
(before? local today) (label :t/datetime-yesterday)
|
|
|
|
:else (today-format-fn local)))))
|
|
|
|
|
|
|
|
(defn day-relative [ms]
|
|
|
|
(when (> ms 0)
|
|
|
|
(to-short-str ms #(label :t/datetime-today))))
|
2016-05-20 09:41:55 +00:00
|
|
|
|
2016-06-30 16:00:44 +00:00
|
|
|
(defn format-time-ago [diff unit]
|
|
|
|
(let [name (label-pluralize diff (:name unit))]
|
|
|
|
(gstring/format "%s %s %s" diff name (label :t/datetime-ago))))
|
|
|
|
|
2016-08-04 15:36:13 +00:00
|
|
|
(defn time-ago [time]
|
|
|
|
(let [diff (t/in-seconds (t/interval time (t/now)))]
|
|
|
|
(if (< diff 60)
|
|
|
|
(label :t/active-online)
|
|
|
|
(let [unit (first (drop-while #(or (>= diff (:limit %))
|
|
|
|
(not (:limit %)))
|
|
|
|
units))]
|
|
|
|
(-> (/ diff (:in-second unit))
|
|
|
|
Math/floor
|
|
|
|
int
|
2016-06-30 16:00:44 +00:00
|
|
|
(format-time-ago unit))))))
|
2016-08-04 15:36:13 +00:00
|
|
|
|
|
|
|
(defn to-date [ms]
|
|
|
|
(from-long ms))
|
|
|
|
|
2016-05-20 09:41:55 +00:00
|
|
|
(defn now-ms []
|
|
|
|
(to-long (now)))
|