📜  Java8 Clock类

📅  最后修改于: 2020-10-01 06:37:39             🧑  作者: Mango

Java Clock类

Java Clock类用于使用时区提供对当前时刻,日期和时间的访问。它继承了Object类。

Java Clock类声明

我们来看一下java.time.Clock类的声明。

public abstract class Clock extends Object

Java Clock方法

Method Description
abstract ZoneId getZone() It is used to get the time-zone being used to create dates and times.
abstract Instant instant() It is used to get the current instant of the clock.
static Clock offset(Clock baseClock, Duration offsetDuration) It is used to obtain a clock that returns instants from the specified clock with the specified duration added
static Clock systemDefaultZone() It is used to obtain a clock that returns the current instant using the best available system clock, converting to date and time using the default time-zone.
static Clock systemUTC() It is used to obtain a clock that returns the current instant using the best available system clock, converting to date and time using the UTC time zone.

Java Clock类示例:getZone()

import java.time.Clock;
public class ClockExample1 {
  public static void main(String[] args) {
    Clock c = Clock.systemDefaultZone();    
    System.out.println(c.getZone());
  }
}

输出:

Asia/Calcutta

Java Clock类示例:Instant()

import java.time.Clock;
public class ClockExample2 {
  public static void main(String[] args) {
    Clock c = Clock.systemUTC();
    System.out.println(c.instant());
  }
}

输出:

2017-01-14T07:11:07.748Z

Java Clock类示例:systemUTC()

import java.time.Clock;
public class ClockExample3 {
  public static void main(String[] args) {
    Clock c = Clock.systemUTC();
    System.out.println(c.instant());
  }
}

输出:

2017-01-14T07:11:07.748Z

Java Clock类示例:offset()

import java.time.Clock;
import java.time.Duration;
public class ClockExample4 {
  public static void main(String[] args) {
    Clock c = Clock.systemUTC();
    Duration d = Duration.ofHours(5);
    Clock clock = Clock.offset(c, d);  
    System.out.println(clock.instant());
  }
}

输出:

2017-01-14T14:15:25.389Z