How to Convert java.util.Date to java.sql.Date

06 May 2023 Balmiki Mandal 0 Core Java

How to Convert java.util.Date to java.sql.Date in Java?

The job of converting java.util.Date to java.sql.Date is fairly simple but sometimes it can be tricky. The cause is that the java.sql.Date inherits from java.util.Date and thus could lead to confusion while writing the code. It is important to remember that these two classes have different formats; one is used for representing date and time objects, while the other is only used for representing date objects.

Sample Code:

//Create a java.util.Date object
java.util.Date utilDate = new java.util.Date();

//convert it to java.sql.Date
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

In the above example, we are creating an instance of java.util.Date which is then converted to java.sql.Date by passing in the milliseconds since the epoch (January 1, 1970 00:00:00 GMT) which is obtained from the getTime() method of java.util.Date.

Another Approach to Converting java.util.Date to java.sql.Date:

We can also use a single line code to convert the java.util.Date to java.sql.Date. Here’s the sample code which does the same as the above example.

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

We can see that the same operation is performed in a single line by instantiating the java.util.Date object and using the getTime() method to extract the milliseconds since the epoch.

Conclusion

We have seen two approaches to convert java.util.Date to java.sql.Date. In both the approaches, we pass in the milliseconds since epoch acquired from the getTime() of java.util.Date. It is important to remember that there is a significant difference between java.util.Date and java.sql.Date and therefore should not be confused while coding for them.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.