Java的java.time包提供日期,时间,实例和持续时间的API。它提供了各种类,例如Clock,LocalDate,LocalDateTime,LocalTime,MonthDay,Year,YearMonth等。与以前的替代方法相比,使用此软件包的类,您可以以更简单的方式获取与日期和时间相关的详细信息。
Java.time.LocalDate-此类表示ISO- 8601日历系统中不带时区的日期对象。
此类的now()方法从系统时钟获取当前日期。
isAfter()方法接受类ChronoLocalDate(表示无时区,或者时间的日期)的目的,如果当前日期成功给定日期的特定日期与当前一个并返回比较真实的(否则,则返回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 "); } } }
Enter the year: 2019 Enter the month: 06 Enter the day: 25 Current date succeeds the given date
Enter the year: 2020 Enter the month: 10 Enter the day: 2 Current date precedes the given date
Enter the year: 2019 Enter the month: 07 Enter the day: 25 Current date is equal to the given date