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:19

Actually you may not use SimpleDateFormat, you can use something like this;

  @JsonSerialize(using=JsonDateSerializer.class)
  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
  private Date blkDate;

This way you can directly get the date with format as specified.

查看更多
无色无味的生活
3楼-- · 2019-01-02 20:21

Its very simple though conditions in this answer are in mysql the column datatype is datetime and you want to send data from java code to mysql:

java.util.Date dt = new java.util.Date();
whatever your code object may be.setDateTime(dt);

important thing is just pick the date and its format is already as per mysql format and send it, no further modifications required.

查看更多
明月照影归
4楼-- · 2019-01-02 20:24

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));
查看更多
永恒的永恒
5楼-- · 2019-01-02 20:26

Use the following code to insert the date into MySQL. Instead of changing our date's format to meet MySql's requirement, we can help data base to recognize our date by setting the STR_TO_DATE(?, '%l:%i %p') parameters.

For example, 2014-03-12 can be represented as STR_TO_DATE('2014-03-12', '%Y-%m-%d')

preparedStatement = connect.prepareStatement("INSERT INTO test.msft VALUES (default, STR_TO_DATE( ?, '%m/%d/%Y'), STR_TO_DATE(?, '%l:%i %p'),?,?,?,?,?)"); 
查看更多
裙下三千臣
6楼-- · 2019-01-02 20:32

mysql datetime -> GregorianCalendar

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2012-12-13 14:54:30"); // mysql datetime format
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
System.out.println(calendar.getTime());

GregorianCalendar -> mysql datetime

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = format.format(calendar.getTime());
System.out.println(string);
查看更多
登录 后发表回答