如何在 Java 8 中查看一个日期是在另一个日期之前还是之后?
java 8object oriented programmingprogramming更新于 2025/6/28 7:37:17
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(); //获取给定的日期值 LocalDate givenDate = LocalDate.of(year, month, day); //获取当前日期 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