📜  带有示例的Java 8 Clock fixed() 方法

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

带有示例的Java 8 Clock fixed() 方法

Java Clock 类是Java的日期时间 API Java .time.Clock 的一部分。 Java日期时间 API 是从Java版本 8 添加的。

Clock 类的 fixed() 方法返回一个时钟对象,并且 Clock 对象返回同一时刻。通过调用Clock.fixed(parameters)返回时钟对象,只返回与使用参数指定的相同时刻。返回的类对象是不可变的、线程安全的和可序列化的。这种方法的主要用途是在测试中,需要的时钟固定在当前时钟的位置。

句法:

public static Clock fixed(Instant fixedInstant, ZoneId zone)

参数:此方法需要两个强制参数:

  • fixedInstant – 创建 Clock 对象的即时对象。它不能为空。
  • zone -- 时钟对象的时区。它不能为空。

返回值:此方法返回返回同一时刻的时钟对象。

例子:

Input:: 
Instance object as parameter : Instant.parse("2018-08-19T16:45:42.00Z");
TimeZone Object as parameter : ZoneId.of("Asia/Calcutta");

Output::
class object: 

Explanation:: 
when Clock.fixed(Instant.parse("2018-08-19T16:45:42.00Z") is called, 
then the fixed() method will return a clock object
in return with fixed time zone and instance.

下面的程序说明了Java.time.Clock 类的 fixed() 方法:

程序 1:在定义区域时使用 fixed()

// Java program to demonstrate
// fixed() method of Clock class
  
import java.time.*;
  
// create class
public class fixedMethodDemo {
  
    // Main method
    public static void main(String[] args)
    {
  
        // create instance of clock class
        Instant instant = Instant.parse("2018-08-19T16:02:42.00Z");
  
        // create ZoneId object for Asia/Calcutta zone
        ZoneId zoneId = ZoneId.of("Asia/Calcutta");
  
        // call fixed method
        Clock clock = Clock.fixed(instant, zoneId);
  
        // print details of clock
        System.out.println(clock.toString());
    }
}
输出:
FixedClock[2018-08-19T16:02:42Z, Asia/Calcutta]

程序 2:将 fixed() 用于默认区域

// Java program to demonstrate 
// fixed() method of Clock class
  
  
import java.time.*;
  
// create class
public class fixedMethodDemo {
  
    // Main method
    public static void main(String[] args)
    {
        // create instance of clock class
        Instant instant = Instant.now();
  
        // create ZoneId for defaultZone which is UTC
        ZoneId zoneId = ZoneId.systemDefault();
  
        // call fixed method
        Clock clock = Clock.fixed(instant, zoneId);
  
        // print details of clock
        System.out.println(clock.toString());
    }
}
输出:
FixedClock[2018-08-21T08:10:32.498Z, Etc/UTC]

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