How to store Java Date to Mysql datetime with JPA - java

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)
);

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.

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.

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.

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));

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);

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);

java.util.Date date = new Date();
Object param = new java.sql.Timestamp(date.getTime());
preparedStatement.setObject(param);

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'),?,?,?,?,?)");

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.

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.

I still prefer the method in one line
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())

If using java 8 or higher , try to use LocalDateTime. That was the correct type if you are using DATETIME as mysql data type.
Below is example for conver current time to "2009-09-22 08:08:11" format
LocalDateTime currentTime = LocalDateTime.parse(LocalDateTime.now().toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

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()));

Related

Time String to time representation Java

I have a string like this 210115 I want to represent it as 21:01:15 any ideas?.
I tried using Gregorian calendar but it adds date to it which I don't want
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Date date = new Date();
try{
date = sdf.parse("210115");
}
catch(Exception e){
}
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
System.out.print(calendar.getTime());
Output is Thu Jan 01 21:01:15 UTC 1970 but what I want is just 21:01:15
Thanks.
To output a formatted date, you use another SimpleDateFormat object with a pattern with the format you want.
In this case, it sounds like you might want to use something like
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println( outputFormat.format(date) );
So what you want is just a time, without time zone. I would recommend using the LocalTime class, which is exactly that, instead of the Date class.
LocalTime time = LocalTime.parse("210115", DateTimeFormatter.ofPattern("HHmmss"));
If u r getting the date string in "210115" this format and you want it in "21:01:15" format then why are you using date format.
Simply do string operation as:
String time="210115";
String newtime=time.substring(0,2)+":"+time.substring(2,4)+":"+time.substring(4,6);
System.out.println(newtime);
you will get the required format.21:01:15

How to store time from java.util.Date into java.sql.Date

I want to convert java.util.Date to java.sql.Date but I want hours, minutes, and seconds as well but java.sql.Date can be used only to store date(no time) . I tried the below code but it is giving only year, month, and day for the java.sql.Date object.
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date parsed = format.parse("20110210120534");
System.out.println(format.parse("20110210120534"));
java.sql.Date sql = new java.sql.Date(parsed.getTime());
System.out.println("SQL date is= "+sql);
Current output:
2011-02-10
Desired output:
2011-02-10 12:05:34
The java.sql.Date type is used to store only date (no time) information, as it maps to the SQL DATE type, which doesn't store time. What its toString() method does is:
Formats a date in the date escape format yyyy-mm-dd.
To achieve the desired output you can use java.sql.Timestamp, which stores date and time information, mapping to the SQL TIMESTAMP type. Its toString() method outputs what you need:
Formats a timestamp in JDBC timestamp escape format: yyyy-mm-dd hh:mm:ss.fffffffff, where ffffffffff indicates nanoseconds.
Example:
java.text.DateFormat format = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
java.util.Date date = format.parse("20110210120534");
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
System.out.println(timestamp); // prints "2011-02-10 12:05:34.0"
As other folks said, you need to use java.sql.TimeStamp.
public class Test {
public static void main(String[] args) {
java.util.Date date = new java.util.Date();
java.sql.Timestamp sqlTimeStamp = new java.sql.Timestamp(date.getTime());
System.out.println("util-date:" + date);
System.out.println("sql-timestamp:" + sqlTimeStamp );
}
}
http://tutorials.jenkov.com/java-date-time/java-sql-date.html

How do I pass a Date as SQL parameter in Java without losing the time part? [duplicate]

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 8 years ago.
For example, I have this String: 06/10/2013 18:29:09. I want to convert this string and put it in a SQL database (as Date).
How can I convert this to an sql date, so that it could be inserted into a database? I want the hours minutes and seconds to remain as well.
I tried the following:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date javaDate = sdf.parse("06/10/2013 18:29:09");
java.sql.Date date = new java.sql.Date(javaDate.getTime());
The problem is here:
java.sql.Date date = new java.sql.Date(javaDate.getTime());
java.sql.Date stores the date part of your timestamp. If you want/need to handle both date and time, use java.sql.Timestamp instead:
java.sql.Timestamp date = new java.sql.Timestamp (javaDate.getTime());
More info:
Date vs TimeStamp vs calendar?
You will use a SimpleDateFormat object to parse the string to java.util.date and then use the getTime() method to instantiate a java.sql.Date.
String input = "06/10/2013 18:29:09";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
java.util.Date dt = sdf.parse(input);
java.sql.Date dtSql = new java.sql.Date(dt.getTime());
If you are working with String type for date input and then you want to save that in a database like MySQL, you should use an appropriate Date Format for it. There's a class called "SimpleDateFormat" which you can use for that purpose. You can find a sample in the following link, also a brief explanation on how it works. Hope it helps.
Example: http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm
Best Regards.
Here's a simple demo. In a Database table like this.
You can insert into it like this.
//the SQL statement for creating the database table
create table user(id, integer primary key, username varchar(100), date_created varchar(100));
//the java code to insert into the table created above.
try{
String date = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss").format(new Date());
String sql = "insert into user(username, date_created) values('olupotd', '"+date+"')";
int done = statement.executeUpdate(sql);
if(done > 0)
//inserted
else
//not inserted.
}catch(java.sql.SQLException e){}
Hope that helps

How to convert a date from a Datepicker to Mysql DATETIME format using java?

I have a date (05/15/2013) which is from a HTML Datepicker. I want to save this value in a mySQL column, which is the type of DATETIME. Format should be yyyy-MM-dd.
you can use this
STR_TO_DATE
STR_TO_DATE(string, '%d/%m/%Y')
You can specify the format as per your requirement
You could use joda time with date formatters like this:
DateTime dateTime = DateTime.parse("05/15/2013", DateTimeFormat.forPattern("mm/dd/yyyy"));
String result = dateTime.toString(DateTimeFormat.forPattern("yyyy-mm-dd"));
You can use java.text.SimpleDateFormat class, e.g.
String pattern = "dd/MM/yyyy";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
Date today = new Date();
String output = formatter.format(today);
You can find more on official Oracle tutorial page.
You can try this
String new_date_string = your_date_string.replace("/", "-");
System.out.println(str);
or you can use regex
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(new_date_string);

Time not entered in mysql ? Java

I have a datetime field in mysql table and i am using JPA for persisting data but only date goes in database. Time always shows 00:00:00. What should i do?
I am not doing any manipulation with Date. All i do is to assign new Date() to a variable and store it in database.
What am i doing wrong?
Use the annotation #Temporal(TemporalType.TIMESTAMP)
Example below:
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Tips like these can be found on http://www.java-tips.org

Categories