Java Convert from Date to LocalDateTime


To convert a java.util.Date object to a java.time.LocalDateTime object with the format “yyyy-MM-dd” in Java, you can follow these steps:

  1. Convert the java.util.Date object to a java.time.LocalDate object using the toInstant() and atZone() methods.
  2. Create a java.time.LocalTime object with a default value of midnight (00:00:00).
  3. Combine the java.time.LocalDate and java.time.LocalTime objects into a java.time.LocalDateTime object using the atTime() method.

Here’s an example of how to do this:

import java.util.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class DateToLocalDateTimeExample {
    public static void main(String[] args) {
        Date date = new Date();
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalTime localTime = LocalTime.MIDNIGHT;
        LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDateTime = localDateTime.format(formatter);
        System.out.println(formattedDateTime);
    }
}

In this example, we first create a java.util.Date object using the default constructor, which sets the date to the current date and time. We then convert the java.util.Date object to a java.time.LocalDate object using the toInstant() and atZone() methods. We create a java.time.LocalTime object with a default value of midnight (00:00:00) and combine the java.time.LocalDate and java.time.LocalTime objects into a java.time.LocalDateTime object using the atTime() method.

Finally, we create a DateTimeFormatter object with the desired format of “yyyy-MM-dd” and format the java.time.LocalDateTime object using the format() method. The resulting formatted string is then printed to the console.

The output of the above code might look something like this:

2022-05-06

Note that the timezone used in this example is the system default timezone. You can change the timezone by passing a different ZoneId object to the atZone() method.