I need to insert the current date and time (milliseconds) into MySQL. I did the following:
long time = System.currentTimeMillis();
java.sql.Timestamp timestamp = new java.sql.Timestamp(time);
System.out.println("Time in milliseconds :" + timestamp);
And I got the time in milliseconds correctly (e.g. 2013-03-21 00:08:33.523). However, I need to insert this information into MySQL database. I tried the following using PreparedStatement
prepStmt.setTimestamp(2,timestamp);
But the time is inserted without milliseconds (e.g. 2013-03-21 00:08:33).
How can I insert the time with milliseconds.
EDIT: The column in the database is of DATETIME
type.
java.util.Date date = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
preparedStatement.setTimestamp(1, timestamp);
It the column is of type DATETIME use the setDate method of PreparedStatement.
java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
stmnt.setDate(1, date);
You can create a method getCurrentTimeStamp() and call it from JDBC statement
preparedStatement.setTimestamp(4,getCurrentTimeStamp());
Method:
private static java.sql.Timestamp getCurrentTimeStamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
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