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
@Test public void method4(){ LocalDate localDate = LocalDate.now(); System.out.println("localDate: "+localDate); Instant instant = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant(); Date date = Date.from(instant); System.out.println("date: "+date); } 输出结果 localDate: 2018-11-19 date: Mon Nov 19 00:00:00 CST 2018
@Test public void method5(){ LocalDateTime localDateTime = LocalDateTime.now(); LocalDate localDate = localDateTime.toLocalDate(); System.out.println(localDate); } @Test public void method6(){ LocalDate localDate = LocalDate.now(); LocalDateTime localDateTime = localDate.atStartOfDay(); System.out.println(localDateTime); }
@Test public void method1(){ Date d1 = new Date(); System.out.println("date: "+d1); Instant instant = d1.toInstant(); LocalDateTime local1 = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); System.out.println("LocalDateTime: "+local1); } 输出结果 date: Mon Nov 19 09:37:14 CST 2018 LocalDateTime: 2018-11-19T09:37:14.063
@Test public void method2(){ Date d1 = new Date(); System.out.println("date: "+d1); Instant instant = d1.toInstant(); LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); LocalDate ld = ldt.toLocalDate(); System.out.println("LocalDate: "+ld); } 输出结果 date: Mon Nov 19 09:46:30 CST 2018 LocalDate: 2018-11-19