Java Program to conver java.util.Date to java.sql.Date.
Objective
Write a Java program to convert a java.util.Date to a java.sql.Date for database insertion.
Algorithm / Approach
- Instantiate a
java.util.Dateobject (which contains both date and time). - Extract the raw time in milliseconds using
ud.getTime(). - Pass those milliseconds into the constructor of a new
java.sql.Dateobject. - Print both dates to observe the formatting differences.
Test.java
class Test {
public static void main(String [] ar){
java.util.Date ud;
java.sql.Date sd;
ud = new java.util.Date();
sd = new java.sql.Date(ud.getTime());
System.out.println("UTIL DATE: "+ud);
System.out.println("SQL DATE : "+sd);
}
}
Expected Output
UTIL DATE: Thu Apr 13 21:54:26 IST 2017 SQL DATE : 2017-04-13
Explanation of the Program
- This is a very common requirement when working with JDBC.
java.util.Dateis the standard Java date, representing both the day AND the exact time.java.sql.Dateis a specialized wrapper used by JDBC to represent SQL DATE types, which strictly hold only the Year, Month, and Day (no time data). By passing the milliseconds into the SQL Date constructor, it truncates the time portion automatically.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)