We normally use java.util.Date object for representing a Date in java programs. However, while writing to database table column, we need to convert it to a java.sql.Date.
For this, we can use the following constructor of java.sql.Date :
public Date(long date_in_milliseconds)
This constructor creates a java.sql.Date object using the given milliseconds time value.
Here is an example for the same :
Example : convert java.util.Date to java.sql.Date
In this example, we create a java.util.Date object representing current date and convert it to a java.sql.Date object.
package com.topjavatutorial; import java.text.DateFormat; import java.text.SimpleDateFormat; public class DateUtilDemo { public static void main(String[] args) { java.util.Date todayUtilDate = new java.util.Date(); System.out.println("java.util.Date = " + todayUtilDate); DateFormat df = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss"); System.out.println("Formated java.util.Date : " + df.format(todayUtilDate)); java.sql.Date sqlDate = new java.sql.Date(todayUtilDate.getTime()); System.out.println("java.sql.Date = " + sqlDate); } }
Output
java.util.Date = Sun Dec 11 00:20:18 EST 2016
Formated java.util.Date : 2016-12-11 12:20:18
java.sql.Date = 2016-12-11
Note :
java.util.Date has both date and time information, whereas java.sql.Date only has date information
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post