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

You can convert java.util.Date to java.sql.Timestamp by first taking the long millisecond value using the getTime() method of Date 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 MappingUtils class 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 the java.util.Date object. Instead, you have got three separate methods to set DATE, TIME, and TIMESTAMP in the java.sql package.
Read more »