how to store java date type to mysql date type?
4 Answers
See that your Date
is a java.sql.Timestamp
(especially if you want hours,mins,sec.. to be persisted)
You could convert a java.util.Date
to a Timestamp
like so: new Timestamp(date.getTime())

- 8,238
- 7
- 36
- 53
Use some instance of the Calendar class to convert the date to a string and use the string in your SQL query.

- 90,431
- 16
- 141
- 175
Use a PreparedStatement
to execute the SQL statement, like this:
Date date = ...;
PreparedStatement ps = connection.prepareStatement("INSERT INTO mytable (this, that, datecol) values (?, ?, ?)");
ps.setString(1, "hello");
ps.setString(2, "world");
ps.setTimestamp(3, new java.sql.Timestamp(date.getTime()));
ps.executeUpdate();
When you do it like this, you let the JDBC driver convert it to the format that the database expects, so that your program can remain database independent (you don't need to deal with formatting it in the way that MySQL expects it yourself).
When querying the database, also use PreparedStatement
and use the getTimestamp()
method on the ResultSet
to get the date as a java.sql.Timestamp
object.

- 202,709
- 46
- 318
- 350
java.time
The modern approach uses java.time classes.
The DATE
type in MySQL represents a date only, without time of day and without time zone.
So use LocalDate
with a driver compliant with JDBC 4.2.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( z ) ;
myPreparedStatement.setObject( … , today ) ;
Retrieval.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

- 303,325
- 100
- 852
- 1,154