【问题标题】:how to convert time in seconds to timestamp with time zone in clojure?如何将时间以秒为单位转换为 clojure 中的时区时间戳?
【发布时间】:2019-12-23 18:30:08
【问题描述】:

我正在尝试将时间(以秒为单位)转换为带有时区的时间戳。
我试过了

(defn- seconds-to-milliseconds[time]
  (* time 1000))

(:require [clj-time.coerce :as clj-time])
(clj-time/from-long (seconds-to-milliseconds 1564132000))

结果是:#clj-time/date-time"2019-07-26T09:06:40.000Z"

但是这个结果我不能存储在 Postgres 数据库中,因为我得到了

PSQLException: Can't infer the SQL type to use for an instance of org.joda.time.DateTime. Use setObject() with an explicit Types value to specify the type to use

所以我需要转换它

(clj-time/to-timestamp (clj-time/from-long (seconds-to-milliseconds 1564132000))))

结果是

#inst"2019-07-26T09:06:40.000000000-00:00"

我可以将它存储在 postgres 中,但它没有时区。

谁能帮我将时间(以秒为单位)转换为带时区的时间戳。

【问题讨论】:

    标签: clojure


    【解决方案1】:

    我猜你可以使用普通的旧java.util.Date

    (-> time-in-millis
        (java.util.Date.)
        (save-in-db))
    

    因为无论如何您在输入上都有以毫秒为单位的时间,所以您可以直接使用它,而无需将其转换为可识别时区的日期类型。

    顺便说一句。尽管 PostgreSQL 在内部具有“with time zone”数据类型,但它不会影响值的存储方式(也就是说,您的“timezone”信息无论如何都不会存储!)-> 请参阅Difference between timestamps with/without time zone in PostgreSQL 了解更多详细信息。

    【讨论】:

    • 嘿,我们不能以java.util.Date 格式将日期存储到postgres 数据库中,对吧?我收到org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of java.util.Date. Use setObject() with an explicit Types value to specify the type to use. 错误。
    【解决方案2】:

    找到了解决此问题的方法。通过转换为 UTC 并存储在数据库中。

    (:require [clj-time.coerce :as clj-time])
    (:import (java.util TimeZone))
    
    (TimeZone/setDefault (TimeZone/getTimeZone "UTC"))
    
    (defn- seconds-to-milliseconds
      [time]
      (* time 1000))
    
    (defn seconds-to-timestamp
      [time]
      (clj-time/to-sql-time (clj-time/from-long (seconds-to-milliseconds time))))
    

    示例:(seconds-to-timestamp 1564132000)

    【讨论】:

      猜你喜欢
      • 2018-11-29
      • 2015-06-17
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 2021-08-20
      • 1970-01-01
      相关资源
      最近更新 更多