Convert java.util.Date to java.sql.Date

suggest change

java.util.Date to java.sql.Date conversion is usually necessary when a Date object needs to be written in a database.

java.sql.Date is a subclass of java.util.Date that JDBC uses for an SQL DATE.

The direct conversion from java.util.Date is new java.sql.Date(utilDate.getTime()). That uses the JVM's default time zone and drops the time of day. The example below starts from a LocalDate instead, which has no time of day.

Example

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class UtilToSqlConversion {
    
    public static void main(String args[])
    {
        LocalDate date = LocalDate.of(2016, 7, 22);
        java.sql.Date sqlDate = java.sql.Date.valueOf(date);
        System.out.println("java.sql.Date is : " + sqlDate);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
        System.out.println("formatted date is : " + formatter.format(date));
    }

}
java.sql.Date is : 2016-07-22
formatted date is : 22/07/2016

For new code, prefer java.time.LocalDate; java.sql.Date.valueOf(LocalDate) bridges it to JDBC's legacy date type.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents