0 votes
1 view
in SQL by (20.3k points)

java.util.Date vs java.sql.Date: when to use which and why?

1 Answer

0 votes
by (40.4k points)

Differences between java.util.Date and java.sql.Date are as follows:



In java.util.Date DATE datatype stores the time information.

It maps to the SQL DATE datatype that doesn’t store time information. Therefore, it’s recommended to use over java.util.Date as java.sql.Date doesn’t store second, minute and hour info.

The toString() method of java.util.Date always returns the date in string format monddhh:mm:sszzzyyyy

toString() method of java.sql.Date returns the date in yyyy-mm-ddformat.s

In Java application, java.util.Date refers to a specific instance of time. Without time zone and with millisecond precision. java.util.Date object gives both date and time information 

Whereas, java.sql.Date object gives only date information. 

Java.util.Date is super-class of java.sql.Date.

Therefore, java.sql.DATE inherits all the public method of java.util.DATE like getSeconds(), getMinutes(), getHours() and so on. This override all the time operation from the superclass i.e. java.util.DATE

Now, which one to use it totally depends on the field of SQL type. 

  • PreparedStatement has setters for all three values, #setDate() being the one for sql.Date, #setTime() for sql.Time and #setTimestamp() for sql.Timestamp.

Note: If you are using ps.setObject(fieldIndex, utilDateObject) ; then you can give the normal util.Date to most JDBC drivers.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Dec 19, 2020 in SQL by Appu (6.1k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !