如何在 Java 8 中獲取當前日期、月份和年份?


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

Java.time.LocalDate - 此類表示 ISO-8601 日曆系統中沒有時區的日期物件。此類的 now() 方法從系統時鐘獲取當前日期。

此類還提供其他各種有用的方法,其中包括:

  • getYear() 方法返回一個整數,表示當前 LocalDate 物件中年份欄位。
  • getMonth() 方法返回一個 java.time.Month 類的物件,表示 LocalDate 物件中的月份。
  • getDayOfMonth() 方法返回一個整數,表示 LocalDate 物件中的日期。

示例

以下 Java 示例檢索當前日期,並使用上述指定的方法分別列印日期、年份和月份。

import java.time.LocalDate;
import java.time.Month;
public class LocalDateJava8 {
   public static void main(String args[]) {
      //Getting the current date value
      LocalDate currentdate = LocalDate.now();
      System.out.println("Current date: "+currentdate);
      //Getting the current day
      int currentDay = currentdate.getDayOfMonth();
      System.out.println("Current day: "+currentDay);
      //Getting the current month
      Month currentMonth = currentdate.getMonth();
      System.out.println("Current month: "+currentMonth);
      //getting the current year
      int currentYear = currentdate.getYear();
      System.out.println("Current month: "+currentYear);
   }
}

輸出

Current date: 2019-07-24
Current day: 24
Current month: JULY
Current month: 2019

更新於: 2019年8月7日

24K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.