toInstant()方法被添加到可用于将它们转换到新的日期时间的API原始日期和日历对象。使用ofInstant(Insant,ZoneId)方法得到一个LocalDateTime或ZonedDateTime对象。
让我们来看看他们的操作。
选择使用任何编辑器创建以下java程序在%uA0C:/> JAVA
Java8Tester.javaimport 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]