Tuesday 21 June 2016

How to convert java.util.Date to java.sql.Timestamp in Java - JDBC Example

You can convert java.util.Date tojava.sql.Timestamp by first taking the long millisecond value using the getTime() method ofDate class and then pass that value to the constructor of Timestamp object. Yes, it's as simple as that. For better code reusability and maintenance, you can create a DateUtils or MappingUtilsclass to keep these kinds of utility or mapping functions. Now, the questions comes, why do you need to convert java.util.Date to java.sql.Timestamp? Well, If you are storing date values to database using JDBC, you need to convert a java.util.Date to its equivalent java.sql.Timestamp value. Even though both of them represent date + time value and can be stored in DATETIME SQL type in Microsoft SQl Server database or equivalent in other databases like Oracle or MySQL, there is no method in JDBC API which takes thejava.util.Date object. Instead, you have got three separate methods to set DATE, TIME, and TIMESTAMP in the java.sql package.


Anyway, It's easy to convert a java.util.Date object to java.sql.Timestamp in Java, all you need to do is call the getTime() method to get the long value from 
java.util.Date object and pass it tojava.sql.Timestamp constructor, as shown below:

public Timestamp getTimestamp(java.util.Date date){
  return date == null ? null : new java.sql.Timestamp(date.getTime());
}

Here I am using the ternary operator of Java to first check if the date is null, if yes then I am returning
null, but if it's not null then I am getting the long millisecond value by calling date.getTime() and constructing a Timestamp object. Remember, similar to Hashtable, Timestamp also doesn't use camel case, it's Timestamp and not TimeStamp.



Using ternary operator is also a nice trick to prevent null pointer exception in Java code, without losing readability or adding more lines of code.


Worth noting, Timestamp is a subclass of java.util.Date but you cannot pass a Timestamp instance where a 
java.util.Date is expected because Timestamp class violates Liskov Substitution Principle. According to which subclass doesn't honor the superclass contract. You can read Clean Code by Uncle Bob Martin to learn more about Liskov Substitution principle and other object-oriented design principles.


Java Program to convert Date to Timestamp in JDBC
Now, let's see the Java program to show how you can convert a Date value to Timestamp value for storing into the database using JDBC API. Remember, if you happen to use both java.sql.Date and java.util.Date on same class then uses full name i.e. with the package to avoid ambiguity e.g. java.sql.Date

import java.sql.Timestamp;
import java.util.Date;

/**
 * Java Program to convert java.util.Date to java.sql.Timestamp
 *
 * @author WINDOWS 8
 */
public class DateToTimeStamp {

    public static void main(String args[]) {

        Date today = new Date();

        // converting date to Timestamp in JDBC
        Timestamp timestamp = new Timestamp(today.getTime());
        Timestamp t2 = getTimestamp(today);

        System.out.println("date: " + today);
        System.out.println("timestamp: " + timestamp);
        System.out.println("timestamp2: " + t2);

    }

    /**
     * Utility method to convert Date to Timestamp in Java
     * @param date
     * @return Timestamp
     */
    public static Timestamp getTimestamp(Date date) {
        return date == null ? null : newjava.sql.Timestamp(date.getTime());
    }

}

Output
date: Sat Mar 12 10:53:26 GMT+08:00 2016
timestamp: 2016-03-12 10:53:26.996
timestamp2: 2016-03-12 10:53:26.996


That's all about how to convert java.util.Date to java.sql.Timestamp in Java. You need this conversion while storing Date values e.g. date of birth, maturity date etc into database table where column type is DATETIME. Just remember that similar to Hashtable, Timestamp also doesn't use capital case and if you happen to use both Date classes from java.sql and java.util package in the same class then use full name e.g. 
java.util.Date for util date and java.sql.Date for SQL Date.

No comments:

Post a Comment