I am trying to store in a MySQL record a value java.util.Date
that contains a date and a time together. I have tried with this:
java.util.Date d = new java.util.Date();
plantilla = new SimpleDateFormat("dd/MM/yyyy H:mm");
String tiempo = plantilla.format(d);
And then record the value in MySQL tiempo
but it doesn't work. I don't know if I have to use the java.sql.Date
. In any case, I'm lost.
Can I write directly to the raw a value java.util.Date
in MySQL defining the field with another type other than DATETIME
or is it not recommended?
JDBC does not support the registration of direct instances of
java.util.Date
. Instead, you have three classes in the packagejava.sql
that extend fromjava.util.Date
so you can perform the operation:java.sql.Date
. This type only stores the date. Time information is lost. Equivalent to type sqlDATE
.java.sql.Time
. This type only stores the time. Date information is lost. Equivalent to the sql type `TIME.java.sql.Timestamp
. This type stores both date and time. Equivalent to type sqlDATETIME
andTIMESTAMP
, depending on the database engine support.For your case, I recommend creating an instance of
Timestamp
from your objectjava.util.Date
like so:And to get an object
java.util.Date
fromTimestamp
:You can create and get instances of the other classes
java.sql.Date
andjava.sql.Time
similarly.You can do it, if your field in the database is a date, you have to convert from java.util.Date to java.sql.Date
So you can use a preparedStatement and use date2 for the insert
1.- The first step in your database is to check that the field where the date is going to go is in format
date
ordatetime
that it is the one that allows you to save the dates.2.- You must make a conversion within the program. This is to assign the value:
3.- Then you must separate the fields to compose the date:
4.- At the end, you concatenate these values and give the result to your type variable
date
Annex: http://blog.rolandopalermo.com/2009/12/capturando-fechas-de-un-jdatechooser.html