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

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

package org.kodejava.example.datetime;

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

public class LocalDateToDate {
    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);
    }
}

The result of the code snippet:

LocalDate = 2017-02-14
Date      = Tue Feb 14 00:00:00 WITA 2017
LocalDate = 2017-02-14

LocalDateTime = 2017-02-14T10:34:49.562
Date          = Tue Feb 14 10:34:49 WITA 2017
LocalDateTime = 2017-02-14T10:34:49.562

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

2 Comments

  1. This method does not work for dates before April 1893. A simple test

    @Test
    public void test() {
        LocalDate localDate = LocalDate.of(1893, 3, 1);
        Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        assertEquals("1893-03-01", new SimpleDateFormat("yyyy-mm-dd").format(date));
    }
    

    with the actual value of 1893-06-01 on my machine.

Leave a Reply