본문 바로가기

Web/tip

[LocalDateTime Date] Convert

728x90

Convert java.time.LocalDateTime to java.util.Date

The easiest way of getting a java.util.Date from LocalDateTime is to use an extension to the java.sql.Timestamp — available with Java 8:

public Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert) {
    return java.sql.Timestamp.valueOf(dateToConvert);
}Copy

But of course, an alternative solution is using an Instant object, which we obtain from ZonedDateTime:

Date convertToDateViaInstant(LocalDateTime dateToConvert) {
    return java.util.Date
      .from(dateToConvert.atZone(ZoneId.systemDefault())
      .toInstant());
}

 

 

https://www.baeldung.com/java-date-to-localdate-and-localdatetime

 

Convert Date to LocalDate or LocalDateTime and Back | Baeldung

Learn about possible ways of converting the between old java.util.Date classes and new java.time API.

www.baeldung.com

 

728x90