How to compare two dates in String format in Java?

JavaServer Side ProgrammingProgramming

The java.text.SimpleDateFormat class is used to format and parse a string to date and date to string.

  • One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat object. 
  • To parse/convert a string as a Date object Instantiate this class by passing desired format string.
  • Parse the date string using the parse() method.
  • The util.Date class represents a specific instant time This class provides various methods such as before(), after() and, equals() to compare two dates

Example

Once you create date objects from strings you can compare them using either of these methods as shown below −

Live Demo

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
   public static void main(String args[])throws ParseException {  
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MM");      
      String dateStr1 = "2007-11-25";
      String dateStr2 = "1999-9-12";
      //Parsing the given String to Date object
      Date date1 = formatter.parse(dateStr1);  
      Date date2 = formatter.parse(dateStr2);      
      Boolean bool1 = date1.after(date2);  
      Boolean bool2 = date1.before(date2);
      Boolean bool3 = date1.equals(date2);
      if(bool1){
         System.out.println(dateStr1+" is after "+dateStr2);
      }else if(bool2){
         System.out.println(dateStr1+" is before "+dateStr2);
      }else if(bool3){
          System.out.println(dateStr1+" is equals to "+dateStr2);
      }
   }
}

Output

2007-11-25 is after 1999-9-12

Parse() method of the LocalDate class

The parse() method of the LocalDate class accepts a String value representing a date and returns a LocalDate object.

Example

Live Demo

import java.time.LocalDate;
public class Test {
   public static void main(String args[]){
      String dateStr1 = "2007-11-25";
      String dateStr2 = "1999-9-12";
      LocalDate date1 = LocalDate.parse(dateStr1);
      LocalDate date2 = LocalDate.parse(dateStr1);
      Boolean bool1 = date1.isAfter(date2);  
      Boolean bool2 = date1.isBefore(date2);
      Boolean bool3 = date1.isEqual(date2);
      if(bool1){
          System.out.println(dateStr1+" is after "+dateStr2);
       }else if(bool2){
          System.out.println(dateStr1+" is before "+dateStr2);
       }else if(bool3){
          System.out.println(dateStr1+" is equal to "+dateStr2);
       }
    }
}

Output

2007-11-25 is equal to 1999-9-12

raja
Published on 06-Feb-2021 03:48:36
Advertisements