LocalDateTime isBefore() method in Java

Java 8Object Oriented ProgrammingProgramming

It can be checked if a particular LocalDateTime is before the other LocalDateTime in a timeline using the isBefore() method in the LocalDateTime class in Java. This method requires a single parameter i.e. the LocalDateTime object that is to be compared. It returns true if the LocalDateTime object is before the other LocalDateTime object and false otherwise.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.*;
public class Main {
   public static void main(String[] args) {
      LocalDateTime ldt1 = LocalDateTime.parse("2019-02-15T11:37:12");
      LocalDateTime ldt2 = LocalDateTime.parse("2019-02-18T23:15:30");
      System.out.println("The LocalDateTime ldt1 is: " + ldt1);
      System.out.println("The LocalDateTime ldt2 is: " + ldt2);
      boolean flag = ldt1.isBefore(ldt2);
      if(flag)
         System.out.println("\nLocalDateTime object ldt1 is before LocalDateTime object ldt2");
      else
         System.out.println("\nLocalDateTime object ldt1 is after LocalDateTime object ldt2");
   }
}

Output

The LocalDateTime ldt1 is: 2019-02-15T11:37:12
The LocalDateTime ldt2 is: 2019-02-18T23:15:30
LocalDateTime object ldt1 is before LocalDateTime object ldt2

Now let us understand the above program.

The two LocalDateTime objects ldt1 and ldt2 are displayed. It is checked if the LocalDateTime object ldt1 is before the LocalDateTime object ldt2 in the timeline using the isBefore() method. The returned value is displayed using an if statement. A code snippet that demonstrates this is as follows −

LocalDateTime ldt1 = LocalDateTime.parse("2019-02-15T11:37:12");
LocalDateTime ldt2 = LocalDateTime.parse("2019-02-18T23:15:30");
System.out.println("The LocalDateTime ldt1 is: " + ldt1);
System.out.println("The LocalDateTime ldt2 is: " + ldt2);
boolean flag = ldt1.isBefore(ldt2);
if(flag)
   System.out.println("\nLocalDateTime object ldt1 is before LocalDateTime object ldt2");
else
   System.out.println("\nLocalDateTime object ldt1 is after LocalDateTime object ldt2");
raja
Updated on 30-Jul-2019 22:30:25

Advertisements