Datetime in java

I have the current date and time of the JDBC date and time in the Mysql Database.

It sends the current date and fixed time in the Mysql date type field as 2012/05/25 00:00:00 . Part of the date works very well, but time does not show any value.

I am inserting a 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); 
+8
java jdbc
source share
5 answers

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

2) Install datatye TIMESTAMP in mysql.

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

For PreparedStatement: it could be like this:

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

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

For example, if you use 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())); 
+16
source share

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

+2
source share

I suggest noting the difference between java.util.Date and java.sql.Date

java.util.Date vs java.sql.Date

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

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

+2
source share

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

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

See the discussion from both the database and the jdbc side.

Start with the data type in the database and select the appropriate one. The one that exactly suits your case is DATETIME, as you want the date and hour / min / sec. The DATETIME type is used to store the time of a wall clock, while TIMESTAMP is used for a fixed point in time (several milliseconds after an era). There is also a difference in how they are stored inside MySQL.

Now that you are on the JDBC side, you have the API methods for Date (date only), Timestamp (date and time) and Time (time only). That is all JDBC has to offer. So the API that suits you is setTimestamp

+1
source share

All Articles