How to convert Timestamp to Date in Java?JDBC Example Tutorial

In the last article, I have shown you how to convert Date to Timestamp in Java and today we'll learn about converting timestamp value from database to Date in Java. As you remember, the JDBC API uses separate Date, Time, and Timestamp classes 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 returns 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. Like Date, Timestamp also contains both date and time value, so you won't see empty or zero time we saw previously while converting SQL Date to java.util.Date.

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 a time component but with Timestamp, we have both.

Well, that's again 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 additional nanoseconds values, required to hold the SQL TIMESTAMP fractional seconds value. If you look at the implementation of the 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 the 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.

Btw, If you want to refresh your concepts of equals and hashcode, I suggest you reading Effective Java, where Joshua Bloch has discussed it in great detail.

So even though, methods like getHours(), getMinutes(), getSeconds() don'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 calls the CURRENT_TIMESTAMP method using the PreparedStatment object. This method returns the current database system timestamp as a DATETIME value without the database time zone offset. 

This value is derived from the operating system 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 to the column index. If you remember, columns in JDBC API start 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 instance using that. Now, you have successfully converted a java.sql.Timestamp value to java.util.Date value. You can further check these free JDBC courses to learn more bout it. 

How to convert Timestamp to Date in Java -JDBC ?



Program to convert Timestamp to Date in Java
import java.io.PrintWriter;
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 {
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      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();

      rs.next(); // move the cursor to first column
      currentTimeStamp = rs.getTimestamp(1);

    } catch (Exception e) {
      e.printStackTrace();
    }
    return currentTimeStamp;
  }

}

Output
DriverManager.getConnection("jdbc:sqlserver://localhost:42588;")
trying sun.jdbc.odbc.JdbcOdbcDriver
*Driver.connect (jdbc:sqlserver://localhost:42588;)
trying com.microsoft.sqlserver.jdbc.SQLServerDriver
getConnection returning com.microsoft.sqlserver.jdbc.SQLServerDriver
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 the 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.

You can further read Core Java, Volume II--Advanced Features by Cay S. Horstmann to learn more about JDBC driver and other JDBC concepts, one of the most useful books to learn Java concepts.




Important points

1.Timestamp class has both date and time value as Date but cannot be used in place of java.util.Date because of additional nanosecond value it supports.

2. The Timestamp.equals(Object) method will return false if you compare Timestamp with Date, this is one of the reasons you cannot use Timestamp in place of Date in Java.

3. The Timestamp class has "s" instead of "S" which you might expect given most of the Java classes are written using the Camel case. Another one is Hashtable with "t" instead of "T"

4. Columns are started with index 1 instead of zero hence getTimestamp(1) is used. This is not just related to Timestamp but related to ResultSet in JDBC and you must remember this to avoid java.sql.SQLException: Invalid column index, which often comes when a programmer tries to access the first column with index zero, which is invalid.

5. Don't forget to call ResultSet.next() method before calling get() even if it contains just one row. It is required to move the cursor to the first element. It's a tricky concept to master but if you don't know the right way to check if ResultSet is empty or not, you will struggle to write robust JDBC code in the future.


That's all about how to convert a Timestamp to Date in Java. As a programmer working with Java, JDBC, and database you must know these details about Timestamp and Date class, it's imperative to write correct JDBC code. Unfortunately, Java could have done a better job by standardizing things, as it's a drawback of an API if the programmer needs to remember so many exceptional cases.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.