How do I convert java.util.Date to java.sql.Date?

package org.kodejava.example.jdbc;

import java.util.Date;

public class UtilDateToSqlDate {
    public static void main(String[] args) {
        // Create a new instance of java.util.Date
        Date date = new Date();

        // To covert java.util.Date to java.sql.Date we need to
        // create an instance of java.sql.Date and pass the long
        // value of java.util.Date as the parameter.
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());

        System.out.println("Date    = " + date);
        System.out.println("SqlDate = " + sqlDate);
    }
}

The result of the code snippet above:

Date    = Thu Dec 06 11:03:35 WITA 2018
SqlDate = 2018-12-06

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.