Java中的Date映射到PostgreSQL的timestamp没有时间、分钟和秒。

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

Java Date mapping postgresql timestamp has no time, minutes and seconds

问题

Java在PostgreSQL数据库中使用java.util.Date来保存timeStamp类型的字段,但发现只有年、月和日,没有时间、分钟和秒,这非常奇怪。

我尝试在Java级别将其转换为java.sql.Timestamp,然后保存到数据库的timeStamp字段中,但仍然没有时间。

希望有人能帮助我解决这个问题,以及为什么会导致这样的结果,我对此非常好奇。

英文:

Java uses java.util.Date to save timeStamp type fields in postgresql database, and finds that there is no time, minutes and seconds, only year, month and day, which is very strange.

I have tried to convert it to java.sql.Timestamp at the Java level, and then save it to timeStamp in the database, and found that there is still no time.

I hope someone can help me solve this problem and why it caused such a result. I am very curious about this.

答案1

得分: 1

避免使用旧类

您正在使用可怕的日期时间类,这些类早在几年前就被现代的 java.time 类所取代,这些类在JSR 310中定义。绝不要使用Date类或Timestamp类。

此外,显然您的数据库只存储日期。因此,java.util.Datejava.sql.Timestamp都不适用。它们代表一个时刻,时间轴上的特定点,而不仅仅是一个日期。

DATE 列?

您忘了告诉我们您的列的数据类型。但我猜测该列可能是Postgres类型 DATE,因为您声称只获取年-月-日,没有任何时间。

Postgres中的DATE类型类似于SQL标准中指定的DATE类型。

java.time.LocalDate

对于类似于SQL标准类型 DATE 的列,在JDBC 4.2+中映射的匹配Java类是java.time.LocalDate

写入。

LocalDate ld = LocalDate.of(2023, Month.JANUARY, 23);
myPreparedStatement.setObject(, ld);

检索。

LocalDate ld = myResultSet.getObject(, LocalDate.class);
英文:

Avoid legacy classes

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use either Date class, nor Timestamp.

Furthermore, apparently your database is storing a date-only. So both java.util.Date and java.sql.Timestamp are misfits. Those represent a moment, a specific point on the timeline, not just a date.

DATE column?

You neglected to tell us the data type of your column. But I would guess that the column is of Postgres type DATE, given that you claim to be getting only year-month-day without any time-of-day.

The DATE type in Postgres is akin to the DATE type specified in the SQL standard.

java.time.LocalDate

For a column of a type akin to the SQL standard type DATE, the matching Java class mapped in JDBC 4.2+ is java.time.LocalDate.

Write.

LocalDate ld = LocalDate.of( 2023 , Month.JANUARY , 23 ) ;
myPreparedStatement.setObject( … , ld ) ;

Retrieve.

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

huangapple
  • 本文由 发表于 2023年3月1日 09:29:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75598822.html
匿名

发表评论

匿名网友

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

确定