pondermatic
pondermatic

Reputation: 6583

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"?

Upvotes: 2

Views: 4635

Answers (3)

Erik255
Erik255

Reputation: 1473

I think it's better to use build in timezone support from the formatter

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

instead of (t/default-time-zone) you can use a specific timezone or an offset (see clj-time.core documentation)

(maybe that didn't work in 2013 :) )

Upvotes: 7

Jared314
Jared314

Reputation: 5231

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)

Upvotes: 5

Rörd
Rörd

Reputation: 6681

2013-10-05T19:02:25.641-04:00 is the local time which would be UTC time 2013-10-05T23:02:25.641Z.

If you have a valid UTC time, do not try to convert it with to-local-date-time! to-local-date-time is a convenience function for changing the time zone on a DateTime instance without converting the time. To properly convert the time, use to-time-zone instead.

To format a DateTime without time zone information, use a custom formatter. Your example would be produced by the pattern "yyyy-MM-dd HH:mm:ss".

Example:

Define a UTC time:

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>

Convert it to a local time:

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>

Format the local time:

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

Upvotes: 3

Related Questions