toInstant()方法被添加到可用于將它們轉換到新的日期時間的API原始日期和日歷對象。使用ofInstant(Insant,ZoneId)方法得到一個LocalDateTime或ZonedDateTime對象。
讓我們來看看他們的操作。
選擇使用任何編輯器創建以下java程序在 C:/> JAVA
Java8Tester.java
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.Date;
import java.time.Instant;
import java.time.ZoneId;
public class Java8Tester {
public static void main(String args[]){
Java8Tester java8tester = new Java8Tester();
java8tester.testBackwardCompatability();
}
public void testBackwardCompatability(){
//Get the current date
Date currentDate = new Date();
System.out.println("Current date: " + currentDate);
//Get the instant of current date in terms of milliseconds
Instant now = currentDate.toInstant();
ZoneId currentZone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(now, currentZone);
System.out.println("Local date: " + localDateTime);
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, currentZone);
System.out.println("Zoned date: " + zonedDateTime);
}
}
驗證結果
使用javac編譯器編譯如下類
C:\JAVA>javac Java8Tester.java
現在運行Java8Tester看到的結果
C:\JAVA>java Java8Tester
看到結果。
Current date: Wed Dec 10 05:44:06 UTC 2014
Local date: 2014-12-10T05:44:06.635
Zoned date: 2014-12-10T05:44:06.635Z[Etc/UTC]