datetimeclojuretimezoneclj-time

clj-time and displaying in user's time zone


I've been playing around with to-local-date-time, org.joda.time.DateTimeZone/getDefault, formatters, etc. and I still can't figure out how to get a datetime which I've stored as UTC to display in the user's time zone. Some formatters I can get to display the time, but it shows UTC time with an offset. If I have 2013-10-05T19:02:25.641-04:00, for example, how can I get it to display "2013-10-05 14:02:25"?


Solution

  • You can can apply the timezone with clj-time.core/to-time-zone, using clj-time.core/time-zone-for-offset when you only have the target offset, to get the localized time from your stored UTC.

    There are numerous existing UTC formatters in the clj-time.format/formatters map, but you can always create your own from clj-time.format/formatter, or clj-time.format/formatter-local, and clj-time.format/unparse.

    (require '[clj-time.core :as t]
             '[clj-time.format :as f])
    
    (defn formatlocal [n offset]
      (let [nlocal (t/to-time-zone n (t/time-zone-for-offset offset))]
        (f/unparse (f/formatter-local "yyyy-MM-dd hh:mm:ss aa")
                   nlocal)))
    
    (formatlocal (t/now) -7)