How to see if a date is before or after another date in Java 8?



The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay, Year, YearMonth etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives.

Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system.

The now() method of this class obtains the current date from the system clock.

The isAfter() method accepts an object of the class ChronoLocalDate (representing a date without time zone or, time), compares the given date with the current one and returns true if the current date succeeds the given date (else, it returns false).

The isBefore() method accepts an object of the class ChronoLocalDate (representing a date without time zone or, time), compares the given date with the current one and returns true if the current date preceeds the given date (else, it returns false).

The isEqual() method accepts an object of the class ChronoLocalDate (representing a date without time zone or, time), compares the given date with the current one and returns true if the current date is equal to the given date (else, it returns false).

Example

Following example accepts a date from user compares it with the current date using the above three methods.

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 ");
      }
   }
}

Output 1

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

Output 2

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

Output 3

Enter the year:
2019
Enter the month:
07
Enter the day:
25
Current date is equal to the given date
Updated on: 2019-08-07T11:20:25+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements