4

This is my Clojurescript function,

(defn message-list [messages]
  (println messages) ;; stmt#1
  [:ul.messages
   (for [{:keys [timestamp message name]} @messages]
     ^{:key timestamp}
     [:li
      [:time (.toLocaleString timestamp)] ;; stmt#2
      [:p message]
      [:p " - " name]])])

stmt#1 is printing,

#<Atom: [{:id 1, :name Adeel Ansari, :message Hello, from the other side., 
          :timestamp #object[Transit$TaggedValue [TaggedValue: LocalDateTime, 2020-01-13T18:19:50.552]]}]>

and stmt#2 is printing,

[TaggedValue: LocalDateTime, 2020-01-13T18:19:50.552]

Now, I would like to print it as, say, 13/01/2020 18:19; how should I go about it? I've no idea how to decode tagged-values.

Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133

2 Answers2

4

You can obtain the value from the TaggedValue using .-rep, and then, you can parse that String using some library.

For example you can parse the date, using cljc.java-time, like this:

(let [tv (t/tagged-value "LocalDateTime" "2019-01-01T11:22:33.123")]
    (cljc.java-time.local-date-time/parse (.-rep tv))) => #object[LocalDateTime 2019-01-01T11:22:33.123]

Or you can use Tick; then your code would look something like,

(ns xx.yy.zz
  (:require ..
            [tick.locale-en-us]
            [tick.alpha.api :as t]
            ..
            ))
...
  (defn message-list [messages]
    ...
       [:li
        [:time (t/format (t/formatter "dd/MM/yyyy HH:mm") (t/parse (.-rep timestamp)))]   
        ...]
    ...)
...
Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
w08r
  • 1,639
  • 13
  • 14
3

Ideally you would provide a handler function directly to transit so that it can convert the value at read time. The same must have been done on the server to create the TaggedValue in the first place.

When constructing the reader you can supply

:handlers {"LocalDateTime" (fn [string-val] (parse-the-timestamp string-val))}

The formatting should be delayed until needed but a TaggedValue should ideally not make it out of the read function since it couples your code to the transit implementation.

Thomas Heller
  • 3,842
  • 1
  • 9
  • 9
  • Thanks, Thomas; this sounds like a very good suggestion. Actually, I was looking into handler, but had no idea about how-to. Your snippet gave me a hint. – Adeel Ansari Jan 17 '20 at 11:22