java LocalDate from date code example

Example 1: localdate to date java

// Localdate to Date
Date.from(localdate.atStartOfDay(ZoneId.systemDefault()).toInstant())

Example 2: java instant to localdatetime

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

// ...

//Convert instant to LocalDateTime, no timezone, add a zero offset / UTC+0
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

Example 3: date to localdate

dateToConvert.toInstant()
      .atZone(ZoneId.systemDefault())
      .toLocalDate();

Example 4: how to turna date into a LocalDateTime java

public LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
    return dateToConvert.toInstant()
      .atZone(ZoneId.systemDefault())
      .toLocalDateTime();
}

Example 5: local date to date java

public LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
    return dateToConvert.toInstant()
      .atZone(ZoneId.systemDefault())
      .toLocalDate();
}

Tags:

Java Example