Convert LocalDate to Date in Java [2 ways]

In this post, I will be sharing how to convert LocalDate to Date in Java. Java 8 has provided many new Date and Time APIs. The Date belongs to java.util package i.e java.util.Date whereas LocalDate belongs to java.time package i.e java.time.LocalDate.

There are two ways to convert LocalDate to Date object:
1. Using toInstant() method [Recommended]
2. Using java.sql.Date

Read Also: Java 8 Interview Questions and Answers

1. Using toInstant() method


Steps For Converting LocalDate to Date:


1. First, we will use ZoneId.systemDefault() method to get system default timezone for e.g "GMT". systemDefault() is a static method.

2. We will pass the above step value to the atStartOfDay() method that returns a ZonedDateTime object. According to Oracle docs, ZonedDateTime is an immutable representation of a date-time with a time-zone.

3. The last step is to call toInstant() method to get the java.util.Date object.

Code:


import java.util.Date;
import java.time.LocalDate;
import java.time.ZoneId;

public class LocalDateToDate
{
    public static void main(String[] args) 
    {
        // Returns default time zone like "GMT"
        ZoneId timeZone = ZoneId.systemDefault();
        System.out.println("Fetch Timezone: " + timeZone);
        
        // Creating the object of LocalDate using year, month, day info
        LocalDate localDate = LocalDate.of(2021,01,23);
        System.out.println("LocalDate: "+ localDate);//format yyyy-MM-dd
        
        // Converting localDate object to Date  
        Date date = Date.from(localDate.atStartOfDay(timeZone).toInstant());
        System.out.println("Date: "+date);
    }
}


Output:
Fetch Timezone: GMT
LocalDate: 2021-01-23
Date: Sat Jan 23 00:00:00 GMT 2021

2. Using java.sql.Date


You can convert LocalDate to Date using java.sql.Date class valueOf() method. This might be the easiest approach but not recommended because java.sql.Date belongs to the database layer and client application must be free from any such dependencies. Also, it lacks support for different timezones.

Code:


import java.util.Date;
import java.time.LocalDate;

public class LocalDateToDate2
{
    public static void main(String[] args) 
    {
        LocalDate localDate = LocalDate.of(2021, 01, 23);
        System.out.println("Date is: "+java.sql.Date.valueOf(localDate));
    }
}


Output:
Date is: 2021-01-23

That's all for today. Please mention in comments in case you have any questions related to convert LocalDate to Date in java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry