如何在Java 8中判斷一個日期是否早於或晚於另一個日期?


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

Java.time.LocalDate - 此類表示 ISO-8601 日曆系統中不包含時區的日期物件。

此類的 `now()` 方法從系統時鐘獲取當前日期。

`isAfter()` 方法接受 `ChronoLocalDate` 類的物件(表示不包含時區的日期或時間),將給定日期與當前日期進行比較,如果當前日期晚於給定日期,則返回 true(否則返回 false)。

`isBefore()` 方法接受 `ChronoLocalDate` 類的物件(表示不包含時區的日期或時間),將給定日期與當前日期進行比較,如果當前日期早於給定日期,則返回 true(否則返回 false)。

`isEqual()` 方法接受 `ChronoLocalDate` 類的物件(表示不包含時區的日期或時間),將給定日期與當前日期進行比較,如果當前日期等於給定日期,則返回 true(否則返回 false)。

示例

以下示例從使用者處接收日期,並使用上述三種方法將其與當前日期進行比較。

import java.time.LocalDate;
import java.util.Scanner;
public class CurentTime {
   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 given date value
      LocalDate givenDate = LocalDate.of(year, month, day);
      //Getting the current date
      LocalDate currentDate = LocalDate.now();
      if(currentDate.isAfter(givenDate)) {
         System.out.println("Current date succeeds the given date ");
      }else if(currentDate.isBefore(givenDate)) {
         System.out.println("Current date preceds the given date ");
      }else if(currentDate.isEqual(givenDate)) {
         System.out.println("Current date is equal to the given date ");
      }
   }
}

輸出 1

Enter the year:
2019
Enter the month:
06
Enter the day:
25
Current date succeeds the given date

輸出 2

Enter the year:
2020
Enter the month:
10
Enter the day:
2
Current date precedes the given date

輸出 3

Enter the year:
2019
Enter the month:
07
Enter the day:
25
Current date is equal to the given date

更新於:2019年8月7日

1K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.