Java 中的 Instant atZone() 方法
java 8object oriented programmingprogramming
Java 中,可以使用 Instant 类中的 atZone() 方法将 Instant 与时区组合起来,创建一个 ZonedDateTime 对象。此方法只需要一个参数,即 ZoneID,并返回 ZonedDateTime 对象。
以下程序演示了此方法
示例
import java.time.*; public class Demo { public static void main(String[] args) { Instant i = Instant.parse("2019-01-13T18:35:19.00Z"); System.out.println("The Instant object is: " + i); ZonedDateTime zdt = i.atZone(ZoneId.of("Australia/Melbourne")); System.out.println("The ZonedDateTime object is: " + zdt); } }
输出
The Instant object is: 2019-01-13T18:35:19Z The ZonedDateTime object is: 2019-01-14T05:35:19+11:00[Australia/Melbourne]
现在让我们理解一下上面的程序。
首先显示当前时刻。然后,使用 atZone() 方法将当前时刻与时区组合,创建一个 ZonedDateTime 对象。ZonedDateTime 对象随即显示出来。以下代码片段演示了此过程:
Instant i = Instant.parse("2019-01-13T18:35:19.00Z"); System.out.println("The Instant object is: " + i); ZonedDateTime zdt = i.atZone(ZoneId.of("Australia/Melbourne")); System.out.println("The ZonedDateTime object is: " + zdt);