Java 9中ofInstant()方法的重要性?
在Java9中,引入了ofInstant()方法进行转换。它是LocalDate,LocalTime和LocalDateTime类的静态方法。此方法将java.time.Instant对象转换为需要时区的LocalDate,形式为java.time.ZoneId。
语法
public static LocalTime ofInstant(Instant instant, ZoneId zone) public static LocalDate ofInstant(Instant instant, ZoneId zone) public static LocalDateTime ofInstant(Instant instant, ZoneId zone)
示例
import java.time.LocalDate; import java.time.LocalTime; import java.time.LocalDateTime; import java.time.Instant; import java.time.ZoneId; public class OfInstantMethodTest { public static void main(String args[]) { Instant instant = Instant.parse("2020-02-05T02:35:15.245Z"); System.out.println("Instant: " + instant); LocalDate ld = LocalDate.ofInstant(instant, ZoneId.of("Asia/Kolkata")); System.out.println("LocalDate: " + ld); LocalTime lt = LocalTime.ofInstant(instant, ZoneId.of("Asia/Kolkata")); System.out.println("LocalTime: " + lt); LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Kolkata")); System.out.println("LocalDateTime: " + ldt); } }
输出结果
Instant: 2020-02-05T02:35:15.245Z LocalDate: 2020-02-05 LocalTime: 08:05:15.245 LocalDateTime: 2020-02-05T08:05:15.245