Java8中 LocalDateTime与Date互相转换
作者:互联网
Java8 LocalDateTime与Date互相转换
1、Date转化成LocalDateTime
/** * LocalDateTime与Date互相转换 * 1、Date转化成LocalDateTime */ @Test void testLocalDateTime(){ Date date = new Date(); Instant instant = date.toInstant(); ZoneId zoneId = ZoneId.systemDefault(); //方式一 ZonedDateTime zonedDateTime = instant.atZone(zoneId); LocalDateTime localDateTime = zonedDateTime.toLocalDateTime(); //方式二 直接使用LocalDateTime.ofInstant LocalDateTime localDateTime1 = LocalDateTime.ofInstant(instant, zoneId); System.out.println("Date:" + date); System.out.println("LocalDateTime:" + localDateTime); System.out.println("localDateTime1:" + localDateTime1); }
运行结果:
Date:Tue Dec 15 19:53:21 CST 2020 LocalDateTime:2020-12-15T19:53:21.232 localDateTime1:2020-12-15T19:53:21.232
2、LocalDateTime转化成Date
/** * 2、LocalDateTime转化成Date */ @Test void testDate(){ LocalDateTime localDateTime = LocalDateTime.now(); ZoneId zoneId = ZoneId.systemDefault(); ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId); Instant instant = zonedDateTime.toInstant(); Date date = Date.from(instant); System.out.println("LocalDateTime:" + localDateTime); System.out.println("Date:" + date); }
运行结果:
LocalDateTime:2020-12-15T19:56:58.022 Date:Tue Dec 15 19:56:58 CST 2020
标签:System,zoneId,date,LocalDateTime,Date,Java8,out 来源: https://www.cnblogs.com/donleo123/p/14140650.html