首页 > 解决方案 > 如何将时间以秒为单位转换为 clojure 中的时区时间戳?

问题描述

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

(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

解决方案


我想你可以使用普通的 old java.util.Date

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

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

顺便提一句。尽管 PostgreSQL 在内部具有“带时区”数据类型,但它不会影响值的存储方式(即您的“时区”信息无论如何都不会存储!) -> 请参阅PostgreSQL中带/不带时区的时间戳之间的差异更多细节。


推荐阅读