Convert java.util.Date to java.sql.date and vice versa.

     To covert java.util.Date to java.sql.Date, Pass the milliseconds time value to the constructor of java.sql.Date class (i.e. Date(long date) ). The java.util.Date class has the method getTime() which returns milliseconds time value. The UtilDateToSqlDate method given below accepts util.Date and returns sql.Date.
Similarly, to convert java.sql.Date to java.util.Date, pass the milliseconds time value to the constructor of java.util.Date class which returns util date. The below SqlDateToUtilDate method accepts sql date and returns util date.
The following code has two static methods to convert util date to sql date and vice versa
import java.sql.Date;
class sqlDate
{
public static void main(String args[])
{
   java.util.Date date1 = new java.util.Date();
   System.out.println("Util Date : "+ date1);

//util date to sql date  
   java.sql.Date date2 =UtilDateToSqlDate(date1);
   System.out.println("Sql Date : " + date2);

//sql date to util date
   java.util.Date date3= SqlDateToUtilDate(date2);
   System.out.println("Back to Util Date : "+ date3);
}

//Method to convert  java.util.Date to java.sql.Date

public static Date UtilDateToSqlDate(java.util.Date utilDate) {
	  Date sqlDate = null;
	  if (utilDate != null)  sqlDate = new Date(utilDate.getTime());
	  return sqlDate;
 }

// Method to convert java.sql.Date to java.util.Date

 public static java.util.Date SqlDateToUtilDate(Date sqlDate) {
	  java.util.Date utilDate = null;
	  if (sqlDate != null)  utilDate = new java.util.Date(sqlDate.getTime());
	  return utilDate;
 }
}
Output

You may also like

Leave a Reply