有时为了兼容 Date 类型需要进行转换。

工作中,有时为了兼容 Date 类型字段需要进行类型转换。

将LocalDate、LocalDateTime与Date之间相互转换方法记录一下:

LocalDateTime 转 Date类型
1
2
3
4
public static Date toDate(LocalDateTime localDateTime) {
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
LocalDate 转 Date 类型
1
2
3
4
public static Date toDate(LocalDate localDate) {
ZoneId zoneId = ZoneId.systemDefault();
return Date.from(localDate.atStartOfDay(zoneId).toInstant());
}

注:LocalDate 会截去 时分秒数据

Date 转 LocalDate
1
2
3
4
public static LocalDate toLocalDate(Date date) {
Instant instant = date.toInstant();
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();
}
Date 转LocalDateTime
1
2
3
4
public static LocalDateTime toLocalDateTime(Date date) {
Instant instant = date.toInstant();
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}