How to convert java.util.Date from java.time.LocalDate?

DeeKay August 12, 2017 at 3:13 am · JAVA API

The following Java code snippet shows how to convert java.util.Date from java.time.LocalDate  and vice versa. In the first part of the code snippet we convert java.util.Date from java.time.LocalDate and back to LocalDate object. In the second part we convert java.time.LocalDate from java.util.Date and back to java.util.Date object.

/****************************************************************************************
 * Created on 08-2017 Copyright(c) https://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.java.datetime;

import java.time.*;
import java.util.Date;

/**
 * Created by https://kodehelp.com
 * Date: 8/11/2017
 */
public class ConvertLocalDateToDate {
    public static void main(String[] args) {
        // Convert java.time.LocalDate to java.util.Date and back to
        // java.time.LocalDate
        LocalDate localDate = LocalDate.now();
        System.out.println("LocalDate ==> " + localDate);

        Date date1 = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        System.out.println("Date ==> " + date1);

        localDate = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        System.out.println("LocalDate ==> " + localDate);
        System.out.println();

        // Convert java.time.LocalDateTime to java.util.Date and back to
        // java.time.LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("LocalDateTime ==> " + localDateTime);

        Date date2 = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        System.out.println("Date ==> " + date2);

        localDateTime = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        System.out.println("LocalDateTime ==> " + localDateTime);
    }
}