How to Convert java.util.Date to java.sql.Timestamp
The java.sql.Timestamp extends java.util.Date class, is a thin wrapper to represent SQL TIMESTAMP, which able to keep both date and time. java.sql.Timestamp is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds - the nanos - are separate.
Convert java.util.Date to java.sql.Timestamp
java.util.Date to java.sql.Timestamp conversion is necessary when a java.util.Date object needs to be written in a database which the column is used to store TIMESTAMP. Example of this data are last login datetime, transaction creation datetime, etc. java.sql.Timestamp used by JDBC to identify an TIMESTAMP type.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class UtilDateToSqlTimestampExample {
public static void main(String[] args) {
java.util.Date utilDate = new java.util.Date();
System.out.println("java.util.Date time : " + utilDate);
java.sql.Timestamp sqlTS = new java.sql.Timestamp(utilDate.getTime());
System.out.println("java.sql.Timestamp time: " + sqlTS);
DateFormat df = new SimpleDateFormat("dd/MM/YYYY hh:mm:ss:SSS");
System.out.println("Date formatted : " + df.format(utilDate));
}
}
java.util.Date time : Fri Aug 02 01:44:51 SGT 2019 java.sql.Timestamp time: 2019-08-02 01:44:51.596 Date formatted : 02/08/2019 01:44:51:596
Per above example, we can convert java.util.Date to java.sql.Timestamp by using the getTime() method of Date class and then pass that value to the constructor of Timestamp object. Date's getTime() method will return the long millisecond value of that object.
Convert java.util.Timestamp to java.sql.Date
And vice versa, java.sql.Date to java.util.Date conversion is necessary when we need to read TIMESTAMP value from database, and pass it to a java.util.Date variable.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class SqlTimestampToUtilDateExample {
public static void main(String[] args) {
java.sql.Timestamp sqlTS = java.sql.Timestamp.valueOf("1997-05-07 21:30:55.888");
System.out.println("java.sql.Timestamp time: " + sqlTS);
java.util.Date utilDate = new java.util.Date(sqlTS.getTime());
System.out.println("java.util.Date time : " + utilDate);
DateFormat df = new SimpleDateFormat("dd/MM/YYYY hh:mm:ss:SSS");
System.out.println("Date formatted : " + df.format(utilDate));
}
}
java.sql.Timestamp time: 1997-05-07 21:30:55.888 java.util.Date time : Wed May 07 21:30:55 SGT 1997 Date formatted : 07/05/1997 09:30:55:888
Putting it All Together
In following example, we will implement the conversion in a simple SQL INSERT and QUERY example. First, we create a test table in our database. As in previous example, this example also using PostgreSQL database. For the sake of showing the difference between DATE datatype and TIMESTAMP datatype, we'll create a table with both types:
create table test_date ( curr_date DATE, curr_timestamp TIMESTAMP );
The next program demonstrates every step you need to convert current date into a date and a timestamp field, and insert it to database table.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class SqlTimestampInsertExample {
public static void main(String[] args) throws Exception {
// (1) connect to postgresql database
String url = "jdbc:postgresql://localhost/coffeeshop";
Class.forName("org.postgresql.Driver");
try (Connection conn = DriverManager.getConnection(url, "barista", "espresso")) {
// (2) set java.sql.Date and Timestamp with current Date (and time)
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
java.sql.Timestamp sqlTS = new java.sql.Timestamp(utilDate.getTime());
// (3) insert java.sql.Date and Timestamp to DB
String sql = "INSERT INTO test_date(curr_date, curr_timestamp) VALUES (?,?)";
try (PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setDate(1, sqlDate);
pst.setTimestamp(2, sqlTS);
// (4) execute update
pst.executeUpdate();
}
}
}
}
And now, check the result using psql (result may very):
$ psql coffeeshop barista Password for user barista: psql (9.2.1) Type "help" for help. coffeeshop=> select * from test_date; curr_date | curr_timestamp ------------+------------------------- 2019-08-02 | 2019-08-02 02:17:35.803 (1 row)
From psql console we can see, that DATE is "2019-08-02" and TIMESTAMP is "2019-08-02 02:17:35.803". Now, we create another program to read from database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SqlTimestampQueryExample {
public static void main(String[] args) throws Exception {
// (1) connect to postgresql database
String url = "jdbc:postgresql://localhost/coffeeshop";
Class.forName("org.postgresql.Driver");
try (Connection conn = DriverManager.getConnection(url, "barista", "espresso")) {
// (2) create statement and query
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM test_date");
while ( rs.next() ) {
java.sql.Date currSqlDate = rs.getDate("curr_date");
java.sql.Timestamp currSqlTS = rs.getTimestamp("curr_timestamp");
java.util.Date currDate = new java.util.Date(currSqlTS.getTime());
// (3) print results
System.out.println("java.sql.Date : " + currSqlDate);
System.out.println("java.sql.Timestamp: " + currSqlTS);
System.out.println("java.util.Date : " + currDate);
}
}
}
}
java.sql.Date : 2019-08-02 java.sql.Timestamp: 2019-08-02 02:17:35.803 java.util.Date : Fri Aug 02 02:17:35 SGT 2019
And if you curious, what happen is the developer make mistakes, and the datatypes switched?
java.sql.Timestamp currSqlTS = rs.getTimestamp("curr_date");
java.sql.Date currSqlDate = rs.getDate("curr_timestamp");
java.util.Date currDate = new java.util.Date(currSqlTS.getTime());
System.out.println("java.sql.Date : " + currSqlDate);
System.out.println("java.sql.Timestamp: " + currSqlTS);
System.out.println("java.util.Date : " + currDate);
Here the result (date/time may vary):
java.sql.Date : 2019-08-02 java.sql.Timestamp: 2019-08-02 00:00:00.0 java.util.Date : Fri Aug 02 00:00:00 SGT 2019
Although not end of the world, the time component is gone for Timestamp.
Conclusion
java.sql.Timestamp used in JDBC to store (and use to retrieve) a TIMESTAMP value. If you need to convert from java.util.Date to java.sql.Timestamp or vice versa, you can use the method getTime() of the source object to get the millisecond value and pass it to target constructor. And again, if you are using Java 8, then better to use new Date/Time API in java.time.* package.