Java 8 Clock instant() 方法
在這篇文章中,我們將學習如何在 Java 的 Clock 類中使用 instant() 方法來獲取時鐘物件的當前時刻。此方法不需要引數,並返回一個表示時鐘當前時間戳的 Instant 例項。Instant 類是 java.time 包 的一部分,表示 UTC 時間軸上的一個特定點。
問題陳述
在 java.time 包中的 Clock 類中,使用 instant() 方法獲取時鐘物件的當前時刻。instant() 方法不需要引數,並返回一個表示系統預設時區當前時間的 Instant 例項。輸入
No input required; it creates a Clock object based on the system's default time zone輸出
The clock is: SystemClock[Etc/UTC]The instance is: 2019-02-07T08:54:18.679Z
獲取時鐘物件當前時刻的步驟
以下是獲取時鐘物件當前時刻的步驟
- 從 java.time 包匯入必要的類 Clock 和 Instant。
- 使用 systemDefaultZone() 方法建立一個 Clock 物件。
- 使用 instant() 方法獲取時鐘物件的當前時刻。
- 列印時鐘物件和獲得的時刻。
獲取時鐘當前時刻的 Java 程式
以下是獲取時鐘當前時刻的示例
import java.time.*;
public class Demo {
public static void main(String[] args) {
Clock c = Clock.systemDefaultZone();
Instant i = c.instant();
System.out.println("The clock is: " + c);
System.out.println("The instance is: " + i);
}
}
輸出
The clock is: SystemClock[Etc/UTC] The instance is: 2019-02-07T08:54:18.679Z
程式碼解釋
在這個程式中,Clock 物件使用 Clock.systemDefaultZone() 方法建立,獲取預設時區的系統時鐘。然後使用 instant() 方法獲取此時鐘的當前時刻。時鐘物件和時刻使用 System.out.println() 列印。Instant 類表示時間軸上的一個點,並以標準 ISO-8601 格式顯示。廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP