Wednesday, October 7, 2015

How to convert java.util.Date to java.sql.Date - JDBC Example


JDBC has their own data types for date and time e.g. java.sql.Date, java.sql.Time and java.sql.TimeStamp to match with database date, time and date time types, we cannot pass java.util.Date directly.
All methods which are suppose to store dates e.g. setDate(input1, input2) expects java.sql.Date, so it becomes essential to know how to convert java.util.Date to java.sql.Date in JDBC.

 You would be surprised to know that java.sql.Date is a subclass of java.util.Date and all it does is suppress or remove time-related fields from java.util.Date.

 It is also a good example of a class which violates Liskov substitution principle, because even though java.sql.Date extends java.util.Date, you cannot pass around it to the method which expect java.util.Date because all time-related methods e.g. getHour(), getMinute() and getSeconds() method throws java.util.NotSupportedException.


Converting java.util.Date to java.sql.Date - Example


Unfortunately, there is no method like toSQLDate() in java.util.Date class to facilitate conversion between util date and SQL date but you can use getTime() method to extract long millisecond value from java.util.Date and create a new java.sql.Date based upon that value as shown below:

Date now = new Date();

java.sql.Date sqlDate = new java.sql.Date(now.getTime());

This is the easiest and right way to convert a java.util.Date to java.sql.Date in Java.


Here is a good java book available on Amazon.Head First Java

No comments:

Post a Comment

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...