Differences between java.util.Date and java.sql.Date

In this post, we will discuss the differences between java.util.Date and java.sql.Date in Java.

Java provides two Date classes, one present in java.util package and the other one in java.sql package. Below are few differences between java.util.Date and java.sql.Date:

1. The java.util.Date represents a specific instant in time in a Java application, with millisecond precision and without timezone. A java.util.Date object represents both date and time information, while java.sql.Date object only stores the date information


2. java.sql.Date maps to the SQL DATE datatype which doesn’t stores time information. This is why we need java.sql.Date in addition to java.util.Date as SQL DATE datatype doesn’t store hour, minute and second information.


3. In order to store a java.util.Date object in Database as SQL DATE datatype, a conversion to java.sql.Date object is required. Similarly a SQL DATE value is retrieved as java.sql.Date object from the database, and a conversion to java.util.Date is needed to use that date in a Java application.


4. The toString() of java.util.Date returns a string representation of this date in mon dd hh:mm:ss zzz yyyy format while toString() method of java.sql.Date formats a date in yyyy-mm-dd format.


5. It’s worth noting that java.sql.Date is a subclass of java.util.Date, so it inherit all public methods of java.util.Date such as getHours(), getMinutes(), getSeconds(), and corresponding set*() methods. Now we have covered that java.sql.Date doesn’t stores the time information, then what do these methods returns?

java.sql.Date actually override all the time operations inherited from java.util.Date, and all these methods are deprecated since SQL Date values do not have a time component. They all throw a java.lang.IllegalArgumentException if invoked as evident from their implementation details:



6. We know that a subclass usually extends the functionality of a parent class, but here java.sql.Date subclass is actually restricting features available in the parent java.util.Date class. So if we pass java.sql.Date to a method which expects a java.util.Date, the code will compile but will throw a java.lang.IllegalArgumentException on runtime.


7. Before we conclude, let’s see how to convert java.util.Date to java.sql.Date and vice versa.

To convert java.util.Date to java.sql.Date in Java –

To convert java.sql.Date to java.util.Date in Java (Since java.sql.Date inherits java.util.Date)-

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of