I'm struggling to understand how to get it to work. I have a prepared statment, and I want to persist a java.util.date. It doesn't work. I tried to cast it to java.sql.Date, and it still doesn't work. what's the issue with java date framework, it's really not straight forward.
You should use java.sql.Timestamp
to store a java.util.Date
in a DATETIME
field. If you check the javadocs of both classes (click the above links!), you'll see that the Timestamp
has a constructor taking the time in millis and that Date
has a getter returning the time in millis.
Do the math:
preparedStatement.setTimestamp(index, new Timestamp(date.getTime()));
// ...
You should not use java.sql.Date
as it represents only the date portion, not the time portion. With this, you would end up with 00:00:00
as time in the DATETIME
field.
For your information only, since Timestamp
is a subclass of java.util.Date
, you could just upcast it whenever you obtain it from the ResultSet
.
Date date = resultSet.getTimestamp("columnname");
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With