Convert LocalDate to Date in Java

This example shows different ways of converting java.time.LocalDate into java.util.Date.

Convert LocalDate to Date Example

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

/**
 * Class which shows different ways of converting java.time.LocalDate into java.util.Date. 
 *  
 * @author sourcecodeexamples.net
 *
 */
public class LocalDateToDateConverter {

    public static Date convertToDateViaSqlDate(LocalDate dateToConvert) {
        return java.sql.Date.valueOf(dateToConvert);
    }

    public static Date convertToDateViaInstant(LocalDate dateToConvert) {
        return java.util.Date.from(dateToConvert.atStartOfDay()
            .atZone(ZoneId.systemDefault())
            .toInstant());
    }

    public static void main(String[] args) {
        System.out.println(convertToDateViaSqlDate(LocalDate.now()));
        System.out.println(convertToDateViaInstant(LocalDate.now()));
    }
}
Output:
2019-06-17
Mon Jun 17 00:00:00 IST 2019

Reference

Comments