How to store Java Date to Mysql datetime…?

2019-01-02 19:35发布

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

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;

11条回答
笑指拈花
2楼-- · 2019-01-02 20:05

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.

查看更多
笑指拈花
3楼-- · 2019-01-02 20:07

it works for me !!

in mysql table

DATETIME

in entity:

private Date startDate;

in process:

objectEntity.setStartDate(new Date());

in preparedStatement:

pstm.setDate(9, new java.sql.Date(objEntity.getStartDate().getTime()));
查看更多
牵手、夕阳
4楼-- · 2019-01-02 20:10

see in the link :

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

The following code just solved the problem:

java.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.

查看更多
低头抚发
5楼-- · 2019-01-02 20:13

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.

查看更多
君临天下
6楼-- · 2019-01-02 20:16
java.util.Date date = new Date();
Object param = new java.sql.Timestamp(date.getTime());    
preparedStatement.setObject(param);
查看更多
步步皆殇っ
7楼-- · 2019-01-02 20:19

you will get 2011-07-18 + time format

long timeNow = Calendar.getInstance().getTimeInMillis();
java.sql.Timestamp ts = new java.sql.Timestamp(timeNow);
...
preparedStatement.setTimestamp(TIME_COL_INDEX, ts);
查看更多
登录 后发表回答