Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert current time in MySQL using Java

Tags:

java

mysql

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.

like image 636
user2192774 Avatar asked Mar 20 '13 21:03

user2192774


3 Answers

java.util.Date date = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
preparedStatement.setTimestamp(1, timestamp);
like image 196
clav Avatar answered Nov 01 '22 10:11

clav


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);
like image 40
Ozzie Avatar answered Nov 01 '22 09:11

Ozzie


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());
 
}
like image 43
Chinmoy Avatar answered Nov 01 '22 09:11

Chinmoy