一.在Java 8中将Date转换为LocalDateTime
方法1:
将Date转换为LocalDatetime,我们可以使用以下方法:
1.从日期获取ZonedDateTime并使用其方法toLocalDateTime()获取LocalDateTime
2.使用LocalDateTime的Instant()工厂方法
示例:
package insping; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; public class Test { public static void main(String[] args) { Date date = new Date(); Instant instant = date.toInstant(); ZoneId zoneId = ZoneId.systemDefault(); LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime(); System.out.println("Date = " + date); System.out.println("LocalDateTime = " + localDateTime); } }
结果:
Date = Fri Jun 16 15:35:26 CST 2017
LocalDateTime = 2017-06-16T15:35:26.970
方法2:
我们也可以使用LocalDateTime的FactoryInput()方法使用系统的默认时区。
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), zoneId);
二.在Java 8中将LocalDateTime转换为Date
要将LocalDateTime转换回java.util.Date,我们可以使用以下步骤:
1.使用atZone()方法将LocalDateTime转换为ZonedDateTime
2.将ZonedDateTime转换为Instant,并从中获取Date
示例:
package insping; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date; public class Test { public static void main(String[] args) { ZoneId zoneId = ZoneId.systemDefault(); LocalDateTime localDateTime = LocalDateTime.now(); ZonedDateTime zdt = localDateTime.atZone(zoneId); Date date = Date.from(zdt.toInstant());
System.out.println("LocalDateTime = " + localDateTime);
System.out.println("Date = " + date);
}
}
结果:
LocalDateTime = 2017-06-16T15:38:48.580
Date = Fri Jun 16 15:38:48 CST 2017
转自:https://blog.csdn.net/hspingcc/article/details/73332380