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