java8 时间类与Date类的相互转化
在转换中,我们需要注意,因为java8之前Date是包含日期和时间的,而LocalDate只包含日期,LocalTime只包含时间,所以与Date在互转中,势必会丢失日期或者时间,或者会使用起始时间。如果转LocalDateTime,那么就不存在信息误差。
1//Date与Instant的相互转化 2Instant instant = Instant.now(); 3Date date = Date.from(instant); 4Instant instant2 = date.toInstant(); 5 6//Date转为LocalDateTime 7Date date2 = new Date(); 8LocalDateTime localDateTime2 = LocalDateTime.ofInstant(date2.toInstant(), ZoneId.systemDefault()); 9 10//LocalDateTime转Date 11LocalDateTime localDateTime3 = LocalDateTime.now(); 12Instant instant3 = localDateTime3.atZone(ZoneId.systemDefault()).toInstant(); 13Date date3 = Date.from(instant); 14 15//LocalDate转Date 16//因为LocalDate不包含时间,所以转Date时,会默认转为当天的起始时间,00:00:00 17LocalDate localDate4 = LocalDate.now(); 18Instant instant4 = localDate4.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant(); 19Date date4 = Date.from(instant);