簡體   English   中英

如何將 Unix 時間戳(以毫秒為單位)轉換為與 PostgreSQL 兼容的時間戳?

[英]How do I convert Unix timestamp in milliseconds to a Timestamp compatible with PostgreSQL?

我有一個 REST 服務,其端點在請求的時間間隔內獲取數據。 請求的間隔下降為兩個 Unix 時間戳,以毫秒為單位,類型為 Long。 像這樣:

Long start = 1622648253010;
Long end = 1622651853010;

我有一個 PostgreSQL 數據庫,它有一個帶有時間戳列的表。 我需要 select 該表中的一些數據,其中時間戳位於兩個 Unix 時間戳之間。 但是 PostgreSQL 不理解 Unix 時間戳,所以我必須在查詢中使用它們之前將這兩個時間戳轉換為 PostgreSQL 兼容時間戳。 轉換應在 Java 中完成,而不是在 SQL 查詢中完成。

我怎么做? 我知道的唯一方法是:

java.sql.Timestamp.from(Instant.ofEpochSecond(
                        start.getSeconds(), start.getNanos()))

但這不起作用。

java.time

java.util日期時間 API 及其格式 API、 SimpleDateFormat已過時且容易出錯。 建議完全停止使用它們並切換到現代日期時間 API *

  1. 將紀元毫秒轉換為OffsetDateTime
long millisStart = 1622648253010L;
OffsetDateTime odtStart = Instant.ofEpochMilli(millisStart).atOffset(ZoneOffset.UTC);
  1. OffsetDateTimePreparedStatement一起使用:
PreparedStatement st = conn.prepareStatement(SELECT * FROM mytable WHERE columnfoo BETWEEN ? AND ?");
st.setObject(1, odtStart);
st.setObject(2, odtEnd);
ResultSet rs = st.executeQuery(); 
while (rs.next()) {
   //...
}
rs.close();
st.close();

Trail: Date Time了解更多關於java.time現代日期時間 API *的信息。


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API級別仍然不符合 Java-8,請檢查Java 8+ API 可通過脫糖如何在 Android 項目中使用 ThreeTenABP

除以 1000 並使用 to_timestamp)

select to_timestamp(1622648253010/1000);
      to_timestamp      
------------------------
 2021-06-02 17:37:33+02

Long類型沒有方法getSeconds()getNanos() 請參閱: https://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html#Timestamp%28long%29

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM