java.util.date to java.sql.date in Java

  1. Convert java.util.Date to java.sql.Date Using getTime()
  2. Convert java.util.Date to java.sql.Date Using SimpleDateFormat and valueOf()

In this article, we will discuss how we can convert java.util.Date to java.sql.Date using two methods - getTime() and valueOf().

The java.util.Date tells the current moment with the exact milliseconds since January 1, 1970 00:00:00 GMT. java.sql.Date tells only the date in the format of SQL in which the JDBC can understand. SQL date only contains years, months, and days, there is no time and time zone present.

Convert java.util.Date to java.sql.Date Using getTime()

In the first example, we use the getTime() method of the java.util.Date class. The getTime() method, when called, returns the number of milliseconds that have passed since January 1, 1970 00:00:00 GMT. We first create an object of java.util.Date and call the getTime() method that returns the milliseconds as a long type.

Next, we create an object of java.sql.Date that accepts milliseconds as an argument in the constructor. We pass timeInMilliSeconds and we get date1 of the java.sql.Date type.

import java.util.Date;

public class UtilDateToSqlDate {
    public static void main(String[] args) {
        Date date = new Date();

        long timeInMilliSeconds = date.getTime();
        java.sql.Date date1 = new java.sql.Date(timeInMilliSeconds);

        System.out.println("SQL Date: " + date1);
    }
}

Output:

SQL Date: 2021-01-22

Convert java.util.Date to java.sql.Date Using SimpleDateFormat and valueOf()

Another method to convert java.util.Date to java.sql.Date is valueOf(). It is a static method present in the java.sql.Date class. valueOf() takes an argument of the string type. This is why we convert java.util.Date to string.

As the java.util.Date returns date with time, we format the date accepted by java.sql.Date that is yyyy-MM-dd. To format the date, we create an object of SimpleDateFormat and pass the format into its constructor. We call simpleDateFormat.format(date) and pass date as an argument to format the date.

Finally, we get the date as a string that we can pass to valueOf() as an argument and get the result as java.sql.Date.

import java.text.SimpleDateFormat;
import java.util.Date;

public class UtilDateToSqlDate {
    public static void main(String[] args) throws IllegalArgumentException {
        Date date = new Date();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String formattedDate = simpleDateFormat.format(date);

        java.sql.Date date1 = java.sql.Date.valueOf(formattedDate);

        System.out.println("SQL Date: " + date1);
    }
}

Output:

SQL Date: 2021-01-22
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Java SQL Date