How to convert java.util.Date to java.sql.Date keeping in hours, minutes, and seconds?


I'm doing a little program in Java. In it I get a date of type java.util.Date , but I need it in java.sql.Date so that I can insert it in the database. But, on that date, I have hour, minute and second and I would like to input all this data. Does anyone know how to do this?



To convert from java.util.Date to java.sql.Date :

java.util.Date a = ...;
java.sql.Date b = new java.sql.Date(a.getTime());

To insert with date and time, use the java.sql.Timestamp class :

java.util.Date a = ...;
java.sql.Timestamp b = new java.sql.Timestamp(a.getTime());

You can use a Timestamp with a PreparedStatement in the setTimestamp(int, Timestamp) . To get one of these from a ResultSet , use the getTimestamp(int) method or the getTimestamp(String) method .

Scroll to Top