Reputation: 20052
I want to insert the current date and time into a columns defined as datetime type.
I typed the following code:
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
PrepStmt.setDate(1, sqlDate);
When I check the database, I find that the date inserted correctly, but the time is: 00:00:00. What is the fix ?
Upvotes: 17
Views: 55780
Reputation: 23
java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
PrepStmt.setTimestamp(1, date);
I solved it using this..
Upvotes: 2
Reputation: 213193
Since you are using datetime
as your column type, you need to use java.sql.Timestamp
to store your date, and PrepareStatement.setTimestamp
to insert it.
Try using this: -
java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
PrepStmt.setTimestamp(1, date);
Upvotes: 29
Reputation: 2005
Sounds like you need
java.sql.Timestamp
The one that your using java.sql.Date
is for dealing with dates only and does not record time. Alternatively you can use java.sql.Time
if you do want time only.
Upvotes: 3
Reputation: 6783
What you need to use is the setTimestamp(int parameterIndex,Timestamp x) method instead of the setDate() method.
One of the ways you can set the timestamp would be as follows:
Timestamp timestamp = new Timestamp(new Date().getTime());
You can then set the parameter as:
PrepStmt.setTimestamp(1, timestamp);
Upvotes: 4
Reputation: 51030
You are using wrong method. You can use PreparedStatement#setTimestamp(int parameterIndex,
Timestamp x)
instead.
Upvotes: 9