How to convert java.util.Date to java.sql.Date?
To convert a java.util.Date
object to a java.sql.Date
object in Java, you can use the java.sql.Date
constructor that takes a long
value as an argument. This value is the number of milliseconds since the epoch (midnight, January 1, 1970 UTC), and it can be obtained using the getTime()
method of the java.util.Date
class.
Here is an example of how to convert a java.util.Date
to a java.sql.Date
:
import java.util.Date;
import java.sql.Date;
public class Main {
public static void main(String[] args) {
Date utilDate = new Date();
long time = utilDate.getTime();
java.sql.Date sqlDate = new java.sql.Date(time);
System.out.println(sqlDate);
}
}
This code creates a java.util.Date
object and gets the number of milliseconds since the epoch using the getTime()
method. It then creates a java.sql.Date
object using the java.sql.Date
constructor that takes a long
value as an argument.
It is important to note that the java.sql.Date
class represents only a date, without a time component. If you want to convert a java.util.Date
object to a java.sql.Timestamp
object, which represents both a date and a time, you can use the java.sql.Timestamp
constructor that takes a long
value as an argument.