如何在 Java 8 中使用時鐘?


Java 的 java.time 包提供有關日期、時間、例項和持續時間的資訊。它提供了各種類,如 Clock、LocalDate、LocalDateTime、LocalTime、MonthDay、Year、YearMonth 等。與以前的替代方案相比,使用此包中的類可以以更簡單的方式獲取與日期和時間相關的資訊。

java.time 包中的Clock 類用於使用時區訪問當前時刻。使用此類可以獲取當前時區、時鐘時刻、當前毫秒數等。

示例

下面的 Java 示例演示了在 Java 中使用 Clock 類的過程。

import java.time.Clock;
import java.time.ZoneId;
public class CurentTime {
   public static void main(String args[]) {
      //Getting the clock
      Clock clock = Clock.systemUTC();
      System.out.println("Current date: "+clock);
      ZoneId id = clock.getZone();
      System.out.println("zoneId: "+clock.getZone());
      System.out.println("current instant: "+clock.instant());
      //Adding one week to the current date
      Clock defaultClock = Clock.systemDefaultZone();
      System.out.println("Default clock: "+clock);
   }
}

輸出

Current date: SystemClock[Z]
zoneId: Z
current instant: 2019-07-25T05:54:06.345Z
Default clock: SystemClock[Z]

更新於: 2019-08-07

188 次瀏覽

開啟你的 職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.