How to Convert Date to LocalDate and LocalDate to Date in Java 8

convert date to localdate

A Date object represents a specific day and time, whereas a LocalDate object only contains date without any time information.

So, conversion between Date and LocalDate is possible if we only care about the date and not the time information.
 

How to Convert Date to LocalDate in Java 8

If you want to convert java.util.Date to java.time.LocalDate, you can do it using following steps :

1) Convert the Date to a ZonedDateTime.
2) Obtain LocalDate from the ZonedDateTime using its toLocalDate() method.

Example : Convert a Date to a LocalDate

package com.topjavatutorial.java8examples;

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

public class LocalDateUtil {

  public static void main(String[] args) {
    Date date = new Date();
    Instant instant = date.toInstant();
    ZoneId zoneId = ZoneId.systemDefault();
    
    LocalDate localDate = instant.atZone(zoneId).toLocalDate();
    System.out.println("Date = " + date);
    System.out.println("LocalDate = " + localDate);
  }
}

The atZone() method returns a ZonedDateTime formed from this Instant at the specified time-zone.

Output :

Date = Fri Dec 23 01:01:48 EST 2016
LocalDate = 2016-12-23
 

How to Convert LocalDate to Date in Java 8

Now, if you want to convert the LocalDate back to java.util.Date, you can do it using following steps :

1) Convert the LocalDate to an Instant using ZonedDateTime.
2) Obtain an instance of Date from the Instant object using from() method

Example : convert LocalDateTime to Date in Java 8

package com.topjavatutorial.java8examples;

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

public class LocalDateUtil {

  public static void main(String[] args) {
    ZoneId zoneId = ZoneId.systemDefault();
    LocalDate localDate = LocalDate.now();
    ZonedDateTime zdt = localDate.atStartOfDay(zoneId);

    Date date = Date.from(zdt.toInstant());

    System.out.println("LocalDate = " + localDate);
    System.out.println("Date = " + date);
  }
}

Output :

LocalDate = 2016-12-23
Date = Fri Dec 23 00:00:00 EST 2016

© 2016 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags