[java] Convert java.time.LocalDate into java.util.Date type

I want to convert java.time.LocalDate into java.util.Date type. Because I want to set the date into JDateChooser. Or is there any date chooser that supports java.time dates?

This question is related to java java-8 java-time

The answer is


Kotlin Solution:

1) Paste this extension function somewhere.

fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())

2) Use it, and never google this again.

val myDate = myLocalDate.toDate()

public static Date convertToTimeZone(Date date, String tzFrom, String tzTo) {
    return Date.from(LocalDateTime.ofInstant(date.toInstant(), ZoneId.of(tzTo)).atZone(ZoneId.of(tzFrom)).toInstant());
} 

java.time has the Temporal interface which you can use to create Instant objects from most of the the time classes. Instant represents milliseconds on the timeline in the Epoch - the base reference for all other dates and times.

We need to convert the Date into a ZonedDateTime, with a Time and a Zone, to do the conversion:

LocalDate ldate = ...;
Instant instant = Instant.from(ldate.atStartOfDay(ZoneId.of("GMT")));
Date date = Date.from(instant);

java.util.Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());

Simple

public Date convertFrom(LocalDate date) {
    return java.sql.Timestamp.valueOf(date.atStartOfDay());
}

    LocalDate date = LocalDate.now();
    DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
    try {
        Date utilDate= formatter.parse(date.toString());
    } catch (ParseException e) {
        // handle exception
    }

In order to create a java.util.Date from a java.time.LocalDate, you have to

  • add a time to the LocalDate
  • interpret the date and time within a time zone
  • get the number of seconds / milliseconds since epoch
  • create a java.util.Date

The code might look as follows:

LocalDate localDate = LocalDate.now();
Date date = new Date(localDate.atStartOfDay(ZoneId.of("America/New_York")).toEpochSecond() * 1000);

You can use java.sql.Date.valueOf() method as:

Date date = java.sql.Date.valueOf(localDate);

No need to add time and time zone info here because they are taken implicitly.
See LocalDate to java.util.Date and vice versa simpliest conversion?


Here's a utility class I use to convert the newer java.time classes to java.util.Date objects and vice versa:

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

public class DateUtils {

  public static Date asDate(LocalDate localDate) {
    return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
  }

  public static Date asDate(LocalDateTime localDateTime) {
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
  }

  public static LocalDate asLocalDate(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
  }

  public static LocalDateTime asLocalDateTime(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
  }
}

Edited based on @Oliv comment.


This works for me:

java.util.Date d = new SimpleDateFormat("yyyy-MM-dd").parse(localDate.toString());

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#toString--


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to java-8

Default interface methods are only supported starting with Android N Class has been compiled by a more recent version of the Java Environment Why is ZoneOffset.UTC != ZoneId.of("UTC")? Modify property value of the objects in list using Java 8 streams How to use if-else logic in Java 8 stream forEach Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit What are functional interfaces used for in Java 8? java.time.format.DateTimeParseException: Text could not be parsed at index 21 Java 8 lambda get and remove element from list

Examples related to java-time

Why is ZoneOffset.UTC != ZoneId.of("UTC")? java.time.format.DateTimeParseException: Text could not be parsed at index 21 How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds? Convert LocalDateTime to LocalDateTime in UTC LocalDate to java.util.Date and vice versa simplest conversion? JSON Java 8 LocalDateTime format in Spring Boot serialize/deserialize java 8 java.time with Jackson JSON mapper Calculate days between two Dates in Java 8 How to get UTC+0 date in Java 8? Format LocalDateTime with Timezone in Java8