在Java中,Date是一个表示特定时间点的类,精度为毫秒。它是可变的且不线程安全的。
LocalDateTime是一个表示日期和时间(不带时区)的类,精度为纳秒。它是不可变的且线程安全的。
创建Date对象的示例:
Date date = new Date();
创建LocalDateTime对象的示例:
LocalDateTime localDateTime = LocalDateTime.now();
将Date对象转换为LocalDateTime对象,可以使用以下代码:
Date date = new Date();
Instant instant = date.toInstant();
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
将LocalDateTime对象转换为Date对象,可以使用以下代码:
LocalDateTime localDateTime = LocalDateTime.now();
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
Date date = Date.from(zonedDateTime.toInstant());
建议在新代码中使用LocalDateTime而不是Date,因为它提供了更多的功能并且更易于使用。但是,如果需要使用使用Date的旧代码,可以根据需要在两者之间进行转换。