如何使用Clojure的clojure.java-time库解析UTC并格式化为本地时间?

huangapple go评论41阅读模式
英文:

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

问题

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

英文:

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

答案1

得分: 1

确保你正在使用正确的函数:

with-offset

> 将偏移设置为指定值,以确保本地时间保持不变。

(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
> 将偏移设置为指定值,以确保结果具有相同的瞬时时间。

(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"
英文:

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"

huangapple
  • 本文由 发表于 2023年2月24日 12:26:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552638.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定