Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store Java Date to Mysql datetime with JPA

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) ); 
like image 753
Urvish Avatar asked Mar 08 '10 11:03

Urvish


People also ask

How is date stored in database Java Util datetime Java Util datetime?

No time data is kept. In fact, the date is stored as milliseconds since the 1st of January 1970 00:00:00 GMT and the time part is normalized, i.e. set to zero. Basically, it's a wrapper around java. util.

How are Datetimes stored in MySQL?

MySQL retrieves and displays DATE values in ' YYYY-MM-DD ' format. The supported range is '1000-01-01' to '9999-12-31' . The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format.

Does MySQL store datetime as UTC?

time information returned from MySQL is not formatted as 'UTC' so strtotime transforms it into a local time if you are not careful.


1 Answers

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.

like image 58
Haim Evgi Avatar answered Sep 29 '22 00:09

Haim Evgi