📜  Java 8 Clock getZone() 方法和示例

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

Java 8 Clock getZone() 方法和示例

Java Clock 类是Java的日期时间 API Java .time.Clock 的一部分。 Java日期时间 API 是从Java版本 8 添加的。
Clock 类的 getZone() 方法返回用于创建 Clock 类的日期和时间的时区。每个时钟类都需要一个时区来获取当前时间并将该实例转换为日期或时间。因此,此方法返回用于此过程的时区。

句法:

public abstract ZoneId getZone()

返回值:此方法返回用于创建时钟类的时区
例子:

Input:: 
a clock class Object e.g Clock.systemUTC()

Output::
TimeZone e.g. Z

Explanation:: 
when Clock.getZone() is called, then it returns a Time Zone used in Class Object

下面的程序说明了Java.time.Clock 类的 getZone() 方法:
程序1:获取时钟对象的时区,用systemDefaultZone创建,使用getZone()

Java
// Java program to demonstrate getZone()
// method of Clock class
 
import java.time.*;
 
// create class
public class getZoneMethodDemo {
 
    // Main method
    public static void main(String[] args)
    {
 
        // create Clock Object
        Clock clock = Clock.systemDefaultZone();
 
        // get TimeZone of Clock object
        // using  getZone() method
        ZoneId zoneid = clock.getZone();
 
        // print details of TimeZone
        System.out.println("ZoneId for class "
                           + clock + " is " + zoneid);
    }
}


Java
// Java program to demonstrate getZone()
// method of Clock class
 
import java.time.*;
 
// create class
public class getZoneMethodDemo {
 
    // Main method
    public static void main(String[] args)
    {
 
        // create a Zone Id for Calcutta
        ZoneId zoneId = ZoneId.of("Asia/Calcutta");
 
        // create Clock Object by passing zoneID
        Clock clock = Clock.system(zoneId);
 
        // get TimeZone of Clock object
        // using  getZone() method
        // and save ZoneId as zoneid variable
        ZoneId zoneid = clock.getZone();
 
        // print details of TimeZone
        System.out.println("ZoneId for clock is "
                           + zoneid);
    }
}


输出:
ZoneId for class SystemClock[Etc/UTC] is Etc/UTC

程序 2:使用 getZone() 获取时钟对象的时区,区域为“亚洲/加尔各答”。

Java

// Java program to demonstrate getZone()
// method of Clock class
 
import java.time.*;
 
// create class
public class getZoneMethodDemo {
 
    // Main method
    public static void main(String[] args)
    {
 
        // create a Zone Id for Calcutta
        ZoneId zoneId = ZoneId.of("Asia/Calcutta");
 
        // create Clock Object by passing zoneID
        Clock clock = Clock.system(zoneId);
 
        // get TimeZone of Clock object
        // using  getZone() method
        // and save ZoneId as zoneid variable
        ZoneId zoneid = clock.getZone();
 
        // print details of TimeZone
        System.out.println("ZoneId for clock is "
                           + zoneid);
    }
}
输出:
ZoneId for clock is Asia/Calcutta

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