java 8中 java.util.Date 类新增了两个方法,分别是from(Instant instant)和toInstant()方法
// Obtains an instance of Date from an Instant object. public static Date from(Instant instant) { try { return new Date(instant.toEpochMilli()); } catch (ArithmeticException ex) { throw new IllegalArgumentException(ex); } } // Converts this Date object to an Instant. public Instant toInstant() { return Instant.ofEpochMilli(getTime()); }
这两个方法使我们可以方便的实现将旧的日期类转换为新的日期类,具体思路都是通过Instant当中介,然后通过Instant来创建LocalDateTime(这个类可以很容易获取LocalDate和LocalTime),新的日期类转旧的也是如此,将新的先转成LocalDateTime,然后获取Instant,接着转成Date,具体实现细节如下:
@Test public void method3(){ LocalDateTime localDateTime = LocalDateTime.now(); System.out.println("localDateTime: "+localDateTime); Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); Date date = Date.from(instant); System.out.println("date: "+date); } 输出结果 localDateTime: 2018-11-19T10:22:00.712 date: Mon Nov 19 10:22:00 CST 2018