Convert java.time.LocalDate into java.util.Date type
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.
Disclaimer: For illustrating existing java apis only. Should not be used in production code.
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 simplest conversion?