Narayan
Narayan

Reputation: 1269

Datetime in java

I have a JDBC current date and time insert into Mysql Database.

It submits the current date and a fixed time into the Mysql date type field as 2012/05/25 00:00:00. The date part works very fine but the time doesn't shows any value.

I'm inserting the value with the following code:

java.util.Date myDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
PreparedStatement PStmt = con.prepareStatement(Sql query);
PStmt.setDate(1,sqlDate);

Upvotes: 10

Views: 42338

Answers (5)

Bitmap
Bitmap

Reputation: 12538

Use java.sql.Timestamp instead of java.util.Date

For example if you are using PreparedStatement to handle your insert, you can pass your date as;

java.util.Date date = new Date();
pst.setTimestamp(columIndex, new java.sql.Timestamp(date.getTime()));

Upvotes: 20

Shailendra
Shailendra

Reputation: 9102

Although an old post, the answer is simple and depends on your requirement - as per your requirements use DATETIME data type and use the following

java.util.Date date = new Date();
pst.setTimestamp(columIndex, new java.sql.Timestamp(date.getTime()).getTime());

Let's see the reasoning from both the database and jdbc side.

Start from the data type in the database and pick appropriate one. The one which exactly suits your case is DATETIME as you want date and hour/min/sec. DATETIME type is used for storing wall clock time whereas TIMESTAMP is for a fixed point in time (some milliseconds after epoch). There is also difference in how both are stored internally in MySQL.

Now When you come to the JDBC side you have API methods for Date ( only date part), Timestamp (date and time) and Time (only time). That's all what the JDBC has to offer. So now, the API which suits your need is setTimestamp

Upvotes: 1

Sachin J
Sachin J

Reputation: 2191

1) Use java.util.Date in your java class.

2) Set datatye TIMESTAMP in mysql.

Date CreatedDate= new Date(System.currentTimeMillis());

For PreparedStatement: It may be like this:

PreparedStatement PStmt = con.prepareStatement(Sql query);
PStmt.setDate(1,CreatedDate);

Upvotes: 2

bpgergo
bpgergo

Reputation: 16037

I suggest to note the distinction between java.util.Date and java.sql.Date

java.util.Date vs java.sql.Date

EDIT also make sure you have the proper data type in the database (DATE, DATETIME, or TIMESTAMP)

http://dev.mysql.com/doc/refman/5.1/en/datetime.html

Upvotes: 2

Subir Kumar Sao
Subir Kumar Sao

Reputation: 8401

I think you need to have timestamp as column type in mysql.

Upvotes: 2

Related Questions