2013-10-05 34 views
2

我一直在玩到本地日期時間,org.joda.time.DateTimeZone/getDefault,格式化程序等,我仍然無法弄清楚如何獲取我存儲爲UTC的日期時間以顯示在用戶的時區中。有些格式化程序可以顯示時間,但它顯示UTC時間和偏移量。例如,如果我有2013-10-05T19:02:25.641-04:00,我怎樣才能讓它顯示「2013-10-05 14:02:25」?clj時間和在用戶的時區顯示

回答

5

您可以將時區應用於clj-time.core/to-time-zone,使用clj-time.core/time-zone-for-offset(只有目標偏移量)才能從存儲的UTC獲取本地化時間。

clj-time.format/formatters地圖中有許多現有的UTC格式化程序,但您始終可以從clj-time.format/formatterclj-time.format/formatter-localclj-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) 
+2

如果你在模式中使用'hh',你也應該使用'aa'。否則,使用'HH'。 –

+0

是的。更新我的樣本以反映這一點。 – Jared314

3

2013-10-05T19:02:25.641-04:00當地的時間,這將是UTC時間2013-10-05T23:02:25.641Z

如果你有一個有效的UTC時間,做不是嘗試將它轉換爲to-local-date-timeto-local-date-time是一個方便的功能,用於在不轉換時間的情況下更改DateTime實例上的時區。要正確轉換時間,請改用to-time-zone

要格式化沒有時區信息的日期時間,請使用自定義格式器。你的例子將由模式"yyyy-MM-dd HH:mm:ss"產生。

實施例:

定義UTC時間:

time-test.core> (def t0 (date-time 2013 10 05 23 02 25 641)) 
#'time-test.core/t0 
time-test.core> t0 
#<DateTime 2013-10-05T23:02:25.641Z> 

它轉換爲本地時間:

time-test.core> (def t1 (to-time-zone t0 (time-zone-for-offset -4))) 
#'time-test.core/t1 
time-test.core> t1 
#<DateTime 2013-10-05T19:02:25.641-04:00> 

格式的本地時間:

time-test.core> (unparse (formatter-local "yyyy-MM-dd HH:mm:ss") t1) 
"2013-10-05 19:02:25" 
3

我覺得這是更好地從格式化的時區支持使用編譯

(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)) 

,而不是(t/default-time-zone)您可以使用特定的時區或偏移(見CLJ-time.core文檔)

(也許這在2013年沒有工作:))

相關問題