clojureclj-time

How can I “unparse” a date in a specific time zone?


Using clj-time, I can parse a date and time by doing

(def timestamp (format/parse (formatters :date-time-no-ms)
                             "2013-06-03T23:00:00-0500"))
;=> #<DateTime 2013-06-04T04:00:00.000Z>

I can convert this back into a string by doing

(unparse (formatters :year-month-day) timestamp)
;=> "2013-06-04"

This is the year, month, and day of that moment within the UTC time zone. How can I get an unparsed version of the DateTime relative to another time zone? For example, for the example above, I want to specify the UTC–5 time zone and get a string of “2013-06-03”. I have played around with from-time-zone and to-time-zone but can’t seem to find the right combination of functions and arguments.


Solution

  • You'll want to use clj-time.format/with-zone:

    (require '(clj-time [core :as time] [format :as timef]))
    
    (timef/unparse (timef/with-zone (:date-time-no-ms timef/formatters)
                      (time/time-zone-for-id "America/Chicago"))
                   (time/now))
    ;= "2013-06-02T15:20:03-05:00"