How to compare two dates along with time in Java?


The java.time.LocalDateTime class represents the local date and time i.e. the date without time zone, you can use this object instead of Date. This class provides various methods such as isBefore(), isAfter() and, isEqual() to compare two dates −

Example

Live Demo

import java.time.LocalDateTime;
public class Test {
   public static void main(String args[]) {  
      LocalDateTime dateTime1 = LocalDateTime.of(2007, 11, 25, 10, 15, 45);
      LocalDateTime dateTime2 = LocalDateTime.of(1999, 9, 12, 07, 25, 55);      
      Boolean bool1 = dateTime1.isAfter(dateTime2);  
      Boolean bool2 = dateTime1.isBefore(dateTime2);
      Boolean bool3 = dateTime1.isEqual(dateTime2);
      if(bool1){
         System.out.println(dateTime1+" is after "+dateTime2);
      }else if(bool2){
         System.out.println(dateTime1+" is before "+dateTime2);
      }else if(bool3){
          System.out.println(dateTime1+" is equla to "+dateTime2);
      }
   }
}

Output

2007-11-25T10:15:45 is after 1999-09-12T07:25:55

Example

Live Demo

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CreateDateTime {
   public static void main(String args[]) throws ParseException {  
      String dateTimeStr1 = "26-09-1989 8:27:45";
      String dateTimeStr2 = "12-11-2010 2:30:12";
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:SS");      
      Date dateTime1 = formatter.parse(dateTimeStr1);      
      Date dateTime2 = formatter.parse(dateTimeStr2);      
      Boolean bool1 = dateTime1.after(dateTime2);  
      Boolean bool2 = dateTime1.before(dateTime2);
      Boolean bool3 = dateTime1.equals(dateTime2);
      if(bool1){
         System.out.println(dateTimeStr1+" is after "+dateTimeStr2);
      }else if(bool2){
         System.out.println(dateTimeStr1+" is before "+dateTimeStr2);
      }else if(bool3){
         System.out.println(dateTimeStr1+" is equla to "+dateTimeStr2);
      }

   }
}

Output

26-09-1989 8:27:45 is before 12-11-2010 2:30:12

Updated on: 06-Feb-2021

661 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements