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

267 views Asked by At

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

There are 1 answers

1
Basil Bourque On

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 ) ;