Showing posts with label java.sql.Date. Show all posts
Showing posts with label java.sql.Date. Show all posts

java.util.Date to java.sql.Date with timestamp

java.sql.Date() class mainly used in JDBC API. If we need to set date value or need to get date from JDBC result-set then we need to go for java.sql.Date(). Actually java.sql.Date() class extends java.util.Date() class and we can do all operations which we used with java.util.Date() class. Only one main difference between these classes are java.sql.Date() class hold only date and timestamp. Even if try to call methods like getHours(), getMinutes() and getSeconds() which will throw exception like

 at java.sql.Date.getHours(......)

In that case if we need date along with timestamp to deal with JDBC API we can use java.sql.timestamp() class. A thin wrapper around java.util.Date() that allows the JDBC API to identify this as an SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds. A Timestamp also provides formatting and parsing operations to support the JDBC escape syntax for timestamp values.

Now lets see simple example to get current date and time in java.sql.Date() and convert to java.sql.Date() and java.sql.Timestamp()

public class DateTimeTesting {

 public static void main(String[] args) {
  java.util.Date date = new java.util.Date();
  System.out.println("Util DATE       : "+date);
  java.sql.Date sqlDate = new java.sql.Date(date.getTime());
  System.out.println("SQL DATE        : "+sqlDate);
  java.sql.Timestamp sqlDateTime = new java.sql.Timestamp(date.getTime());
  System.out.println("SQL DATE & TIME : "+sqlDateTime);


java.util.Date to java.sql.Date with timestamp