Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to conver java.util.Date to java.sql.Date.

Java Code Example — Utility Programs

ADVERTISEMENT

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

  1. Instantiate a java.util.Date object (which contains both date and time).
  2. Extract the raw time in milliseconds using ud.getTime().
  3. Pass those milliseconds into the constructor of a new java.sql.Date object.
  4. 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.Date is the standard Java date, representing both the day AND the exact time.
  • java.sql.Date is 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)
ADVERTISEMENT