tags:

views:

1220

answers:

4

can any body tell me how can i store Java Date to Mysql datetime...?

when i am trying to do so...only date is stored and time remain 00:00:00 in mysql date stores like this... 2009-09-22 00:00:00

i want not only date but also time...like 2009-09-22 08:08:11 please help me....

EDIT----
i am using JPA(Hibernate) with spring mydomain classes uses java.util.Date but i have created tables using handwritten queries...

this is my create statement

CREATE TABLE ContactUs (id BIGINT auto_increment, userName VARCHAR(30), email VARCHAR(50), subject VARCHAR(100), message VARCHAR(1024), messageType VARCHAR(15), contactUsTime datetime, primary key(id))TYPE=InnoDB;
A: 

see in the link :

http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion

The following code just solved the problem:

j

ava.util.Date dt = new java.util.Date();

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String currentTime = sdf.format(dt);

This 'currentTime' was inserted into the column whose type was DateTime and it was successful.

Haim Evgi
+2  A: 

Are you perhaps using java.sql.Date? While that has millisecond granularity as a Java class (it is a subclass of java.util.Date, bad design decision), it will be interpreted by the JDBC driver as a date without a time component. You have to use java.sql.Timestamp instead.

Michael Borgwardt
+1 for "You have to use java.sql.Timestamp"
Ryan Fernandes
I wouldn't use `java.sql.Date` or `java.sql.Timestamp` in domain classes but I guess this was written before the edit of the OP.
Pascal Thivent
+1  A: 

Probably because your java date has a different format from mysql format (YYYY-MM-DD HH:MM:SS)

do this

 DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 Date date = new Date();
 System.out.println(dateFormat.format(date));
Marcx
A: 

Annotate your field (or getter) with @Temporal(TemporalType.TIMESTAMP), like this:

public class MyEntity {
    ...
    @Temporal(TemporalType.TIMESTAMP)
    private java.util.Date myDate;
    ...
}

That should do the trick.

Pascal Thivent