clj-time并在用户的时区显示

pon*_*tic 2 timezone datetime clojure clj-time

我一直在玩to-local-date-time,org.joda.time.DateTimeZone/getDefault,格式化程序等等,我仍然无法弄清楚如何获得我作为UTC存储的日期时间显示在用户的时区.我可以使用一些格式化程序来显示时间,但它显示带有偏移量的UTC时间.如果我有2013-10-05T19:02:25.641-04:00,我怎么能让它显示"2013-10-05 14:02:25"?

Eri*_*255 6

我认为最好使用格式化程序的内置时区支持

(require '[clj-time.core :as t]
         '[clj-time.format :as f])
(def custom-time-formatter (f/with-zone (f/formatter "yyyy-MM-dd hh:mm:ss")
                                        (t/default-time-zone)))
(f/unparse custom-time-formatter (t/now))
Run Code Online (Sandbox Code Playgroud)

而不是(t/default-time-zone)您可以使用特定的时区或偏移量(请参阅 clj-time.core 文档)

(也许这在 2013 年不起作用:))


Jar*_*314 5

当您只有目标偏移量时,您可以clj-time.core/to-time-zone使用clj-time.core/time-zone-for-offset时区来从您存储的UTC中获取本地化时间.

地图中有许多现有的UTC格式化程序clj-time.format/formatters,但您始终可以创建自己的clj-time.format/formatter,或clj-time.format/formatter-local,和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)
Run Code Online (Sandbox Code Playgroud)

  • 如果你在模式中使用`hh`,你也应该使用`aa`.否则,请使用"HH". (2认同)