Thursday, 13 February 2014

Java: Converting util:Date to sql.Date

Sometimes it is needed to convert java.util.Date to java.sql.Date. An example of this scenario is getting input from user for date of birth through GUI. The date inserted by user will be stored in the database where sql.Date will be required.

Here is one method ho to convert util.Date to sql.Date

java.sql.Date utilDatetoSQL(Date utilDate)
{
           if(utilDate == null)
                   return null;
         
           java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
           System.out.println("Util Date: " + utilDate);
           System.out.println("SQL Date: " + sqlDdate);

           return sqlDate;
}

Another method is by using the Calendar

java.sql.Date utilDatetoSQL(Date utilDate)
{
           java.util.Calendar cal = Calendar.getInstance();

cal.setTime(utilDate);

java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

               return sqlDate;
}



No comments:

Post a Comment