Wednesday, 30 November 2016

How to convert Timestamp to Date in Java - JDBC

The JDBC API uses separate Date, Time and Timestamp class to confirm DATE, TIME and DATETIME data type from the database, but most of the Java object oriented code is written in java.util.Date. This means you need to know how to convert the timestamp to date and vice-versa. You can do by using the getTime() method, which return the number of millisecond from Epoch value. This can be used to create both Timestamp and java.util.Date, hence it acts as a bridge between Date class from java.util package and Date, Time and Timestamp class from the java.sql package.

As I have said before, even though classes from java.sql package extends java.util.Date, including Timestamp they cannot be used in place of java.util.Date. Some of you may ask why? Since Timestamp has both date and time value, it should be able to acts as Date, we understand about java.sql.Date not having time component but with Timestamp we have both.

Well, that's again a very good reasoning and directs your mind to find the missing part of why you cannot use Timestamp in place of date even if it has both date and time part. The answer lies in the Java documentation itself. The Timestamp class is a composite of java.util.Date and an additional nanoseconds values, required to hold the SQL TIMESTAMP fractional seconds value. If you look at the implementation of Timestamp class, you will find that only integral seconds are stored in the java.util.Date component. The fractional seconds - the nanos - are separate.

The Timestamp.equals(Object) method never returns true when passed an object that isn't an instance of java.sql.Timestamp e.g. Timestamp.equals(date) will return false even if they contain same value because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method, hence it also violates the contract of equals method. Also, the hashCode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.

So even though, methods like getHours(), getMinutes(), getSeconds() doesn't throw IllegalArgumentException, because of these differences, you still should not use a Timestamp value in place of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.

Java Program to convert Timestamp to Date with example

Now, let's see our sample Java program to convert a Timestamp value to Date in Java. In this example, our Java program connects to the Microsoft SQL server and call the CURRENT_TIMESTAMP method using PreparedStatment object. This method returns the current database system timestamp as a DATETIME value withtout the database time zone offsert. This value is derived from the operating sytsem of the computer on which the instance of SQL Server is running (see SQL fundamentals).

When we read this value in Java using ResultSet, we use the getTimestamp() method and pass it the column index. If you remember, columns in JDBC API starts with 1 instead of zero, we pass 1. We also need to call the next() method of ResultSet to move the cursor to the first element, otherwise you won't the correct value. Once you got the java.sql.Timestamp value, just call the getTime() and create a java.util.Date instnace using that. Now, you have successfully converted a java.sql.Timestamp value to java.util.Date value.

How to convert Timestamp to Date in Java - JDBC

Program to convert Timestamp to Date in Java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Date;

 * Java Program to convert Timestamp to Date in JDBC.

public class Pattern {

  public static void main(String[] args) {

    Timestamp timestamp = timeStampFromDatabase();
    Date date = new java.util.Date(timestamp.getTime());
    System.out.println("current timestamp from database: " + timestamp);
    System.out.println("converted date in Java: " + date);


  public static Timestamp timeStampFromDatabase() {
    Connection con = null;
    Timestamp currentTimeStamp = null;
    try {
      String url = "jdbc:sqlserver://localhost:42588;";
      DriverManager.setLogWriter(new PrintWriter(System.out, true));
      con = DriverManager.getConnection(url, "sa", "root");

      PreparedStatement ps = con.prepareStatement("select CURRENT_TIMESTAMP");
      ResultSet rs = ps.executeQuery();; // move the cursor to first column
      currentTimeStamp = rs.getTimestamp(1);

    } catch (Exception e) {
    return currentTimeStamp;



trying sun.jdbc.odbc.JdbcOdbcDriver
*Driver.connect (jdbc:sqlserver://localhost:42588;)
getConnection returning
current timestamp from database: 2016-06-17 13:13:56.61
converted date in Java: Fri Jun 17 13:13:56 PST 2016

A couple of important things to learn in this program, first, I have not called the Class.forName() method to explicitly load the JDBC driver because from Java 1.6 onward, it can be automatically loaded by JVM. The second important thing is the use of setting the logger for DriverManager, which will print important details e.g. which JDBC driver it is loading and which host and port it is connecting to database.

The code to convert Timestamp into a java.util.Date is inside main() method, you can see it's quite simple, just take the long millisecond value by calling getTime() on Timestamp and pass it to Date constructor, that's it, you are done.