Search code examples
clojurejava-time

How do I parse UTC and format to local time with Clojure's clojure.java-time library?


I'm sure I'm missing something simple. The goal is to parse a string such as "20230227T010000Z" and then to print out the time in the local time zone.

(as-> "20230227T010000Z" X                        
      (jt/offset-date-time "yyyyMMdd'T'HHmmssX" X) ;#object[java.time.OffsetDateTime "0xf79e8a9" "2023-02-27T01:00Z"]
      (jt/with-offset X (jt/zone-offset))          ;#object[java.time.OffsetDateTime "0x41ec977e" "2023-02-27T01:00-05:00"]     
      (jt/format "hh:mm" X))                       ;"01:00"

This returns "01:00" even though (jt/zone-offset) returns "-05:00".


Solution

  • Make sure you're using the correct function:

    with-offset

    Sets the offset to the specified value ensuring that the local time stays the same.

    (as-> "20230227T010000Z" X
          (jt/offset-date-time "yyyyMMdd'T'HHmmssX" X) 
          (jt/with-offset X -5)         
          (jt/format "hh:mm" X))
    => "01:00"
    

    with-offset-same-instant

    Sets the offset to the specified value ensuring that the result has the same instant.

    (as-> "20230227T010000Z" X
          (jt/offset-date-time "yyyyMMdd'T'HHmmssX" X) 
          (jt/with-offset-same-instant X -5)         
          (jt/format "hh:mm" X))
    => "08:00"