英文:
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.Date
和java.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 ) ;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论