Java8 datetime API, add LocalDate, LocalDateTime, LocalTime and other thread-safe classes:
LocalDate: only the date, such as: 2019-07-13LocalTime: only the time, such as: 08:30LocalDateTime: date + time, such as: 2019-07-13 08:30
1. CONVERT DATE TO LOCALDATE
public static LocalDate date2LocalDate(Date date) {
if(null == date) {
return null;
}
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
2. CONVERT LOCALDATE TO DATE
public static Date localDate2Date(LocalDate localDate) {
if(null == localDate) {
return null;
}
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
2.LocalDateTime is converted to Date
public static Date localDateTime2Date(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
3. LocalDate format
public static String formatDate(Date date) {
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
return localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}