-2

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 4
    Recommendation that you stop using `java.util.Date`/`java.sql.Date`/`java.sql.TimeStamp` where possible and make use of the `java.time.*` class instead. See [Using Java 8 Date and Time classes](https://jdbc.postgresql.org/documentation/query/#using-java-8-date-and-time-classes) for more details – MadProgrammer Mar 01 '23 at 02:41
  • Also make sure the column is not `DATE` and is actually a variant of `TIMESTAMP` (as described in the link in my previous comment) – MadProgrammer Mar 01 '23 at 02:42
  • 1
    What *exactly* is the data type of your column? – Basil Bourque Mar 01 '23 at 02:45
  • 1
    It sounds weird. Are you using JDBC (`PreparedStatement`, for example)? A [mre], please? – Ole V.V. Mar 01 '23 at 12:04
  • 1
    Then I lost the test problem. The previous configuration with problems: the column field type of the database is timeStamp (postgresql), and java uses java.util.Date. But I also think java.time.LocalDateTime should be used, which has been modified. Thank you – wantToADaShen Mar 06 '23 at 01:28

1 Answers1

1

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 ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • https://stackoverflow.com/search?q=myPreparedStatement.setObject https://en.wikipedia.org/wiki/Don%27t_repeat_yourself – BalusC Mar 01 '23 at 15:56