📜  Java中的 ZoneId from() 方法及示例

📅  最后修改于: 2022-05-13 01:55:23.844000             🧑  作者: Mango

Java中的 ZoneId from() 方法及示例

ZoneId类的from()方法用于从作为参数传递的 TemporalAccessor 对象中获取 ZoneId 的实例。该方法基于 TemporalAccessor 获取表示任意日期和时间信息集的区域,该方法将其转换为区域标识。

句法:

public static ZoneId from(TemporalAccessor temporal)

参数:此方法接受单个参数temporal ,表示要转换的时间对象,不能为空。

返回值:该方法返回区域ID ,不能为空。

异常:如果此方法无法将 temporal 转换为 ZoneId,则此方法将引发DateTimeException

下面的程序说明了 from() 方法:
方案一:

// Java program to demonstrate
// ZoneId.from() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create TemporalAccessor object
        ZonedDateTime zoneddatetime
            = ZonedDateTime.parse("2018-10-25T23:12:31.123+02:00[Europe/Paris]");
  
        // get ZoneId from this TemporalAccessor
        ZoneId response = ZoneId.from(zoneddatetime);
  
        // print result
        System.out.println("Zone Id got from "
                           + "TemporalAccessor object \n"
                           + zoneddatetime + "\nis " + response);
    }
}
输出:
Zone Id got from TemporalAccessor object 
2018-10-25T23:12:31.123+02:00[Europe/Paris]
is Europe/Paris

方案二:

// Java program to demonstrate
// ZoneId.from() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create TemporalAccessor object
        ZonedDateTime zoneddatetime
            = ZonedDateTime.now();
  
        // get ZoneId from this TemporalAccessor
        ZoneId response = ZoneId.from(zoneddatetime);
  
        // print result
        System.out.println("Zone Id got from "
                           + "TemporalAccessor object \n"
                           + zoneddatetime + "\nis " + response);
    }
}
输出:
Zone Id got from TemporalAccessor object 
2018-12-10T18:20:03.637Z[Etc/UTC]
is Etc/UTC

参考:
https://docs.oracle.com/javase/10/docs/api/java Java Java)