如何在 Java 8 中檢查兩個日期是否相等?


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

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

java.time.LocalDate 類的 `of()` 方法接受三個整型引數,分別表示年份、月份和日期,並從給定的詳細資訊返回 LocalDate 物件的例項。

java.time.LocalDate 的 `now()` 方法獲取並返回系統時鐘中的當前日期。

java.time.LocalDate 類的 `equals()` 方法接受一個物件(表示 LocalDate),並將其與當前 LocalDate 物件進行比較,如果兩者相等,則此方法返回 true,否則返回 false。如果您傳遞給此方法的物件不是 LocalDate 型別,則此方法返回 false。

示例

下面的 Java 示例從使用者讀取日期值並構造 LocalDate 例項。檢索當前日期並比較這兩個值,然後列印結果。

import java.time.LocalDate;
import java.util.Scanner;
public class LocalDateJava8 {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the year: ");
      int year = sc.nextInt();
      System.out.println("Enter the month: ");
      int month = sc.nextInt();
      System.out.println("Enter the day: ");
      int day = sc.nextInt();
      //Getting the current date value
      LocalDate givenDate = LocalDate.of(year, month, day);
      System.out.println("Date: "+givenDate);
      //Retrieving the current date
      LocalDate currentDate = LocalDate.now();
      //Comparing both values
      boolean bool = givenDate.equals(currentDate);
      if(bool) {
         System.out.println("Given date is equal to the current date ");
      }else {
         System.out.println("Given date is not equal to the current date ");
      }
   }
}

輸出

Enter the year:
2019
Enter the month:
07
Enter the day:
24
Date: 2019-07-24
Given date is equal to the current date

更新於:2019年8月7日

1K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告