根据 Java 日期在 Postgres 中保存时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18132219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:38:04  来源:igfitidea点击:

Saving timestamps in Postgres based on Java dates

javapostgresqlpostgresql-9.1

提问by Dmitrii Pisarenko

I have a Postgres database with a table that contains a timestamp (timeOfProcessing TIMESTAMP).

我有一个包含时间戳 ( timeOfProcessing TIMESTAMP)的表的 Postgres 数据库。

I have a Java datetime value (java.util.Date dateTime) and want to store its value in that timestamp field (without time zone).

我有一个 Java 日期时间值 ( java.util.Date dateTime) 并希望将其值存储在该时间戳字段中(不带时区)。

When I do it using the query

当我使用查询时

"INSERT INTO mytable(..., timeOfCreation, ...) VALUES(..., to_timestamp(" + Long.toString(dateTime.getTime()) + "),...)"

"INSERT INTO mytable(..., timeOfCreation, ...) VALUES(..., to_timestamp(" + Long.toString(dateTime.getTime()) + "),...)"

and then read the saved value (SELECT timeOfCreation FROM mytable), they are different (resultSet.getTimestamp(...).getTime()is not equal to dateTime.getTime()).

然后读取保存的值(SELECT timeOfCreation FROM mytable),它们是不同的(resultSet.getTimestamp(...).getTime()不等于dateTime.getTime())。

How do I need to change the insert statement in order for the datetime to be stored correctly?

我需要如何更改插入语句才能正确存储日期时间?

采纳答案by Kalaji

When inserting, instead of using (dateTime).getTime(), use an SQL timestamp object: new java.sql.Timestamp((dateTime).getTime())

插入时,不要使用 ,而是(dateTime).getTime()使用 SQL 时间戳对象:new java.sql.Timestamp((dateTime).getTime())