java.util.Date
to java.sql.Date
conversion is usually necessary when a Date object needs to be written in a database.
java.sql.Date
is a wrapper around millisecond value and is used by JDBC
to identify an SQL DATE
type
In the below example, we use the java.util.Date()
constructor, that creates a Date object and initializes it to represent time to the nearest millisecond. This date is used in the convert(java.util.Date utilDate)
method to return a java.sql.Date
object
Example
public class UtilToSqlConversion {
public static void main(String args[])
{
java.util.Date utilDate = new java.util.Date();
System.out.println("java.util.Date is : " + utilDate);
java.sql.Date sqlDate = convert(utilDate);
System.out.println("java.sql.Date is : " + sqlDate);
DateFormat df = new SimpleDateFormat("dd/MM/YYYY - hh:mm:ss");
System.out.println("dateFormated date is : " + df.format(utilDate));
}
private static java.sql.Date convert(java.util.Date uDate) {
java.sql.Date sDate = new java.sql.Date(uDate.getTime());
return sDate;
}
}
Output
java.util.Date is : Fri Jul 22 14:40:35 IST 2016
java.sql.Date is : 2016-07-22
dateFormated date is : 22/07/2016 - 02:40:35
java.util.Date
has both date and time information, whereas java.sql.Date
only has date information