Comparing Date using Date.before() and Date.after() Methods in Java

Date.before() and Date.after() methods in Java: In this program, we are taking input two dates and comparing dates using Date.before() and Date.after() methods.

Given (input) two dates in string format, convert them in Date format and then compare them using Date.before() and Date.after() methods in Java.

1) Date1.before(Date2) Method

It returns true if Date1 is less that Date2.

2) Date1.after(Date2) Method

It returns true if Date1 is greater than Date2.

Consider the program:

// Java program to compare date using 
// before() and after() method

import java.text.SimpleDateFormat;
import java.util.*;

public class p22 {
  public static void main(String args[]) {
    try {
      //define date format to take input
      SimpleDateFormat dateF = new SimpleDateFormat("dd/MM/yyyy");

      Scanner sc = new Scanner(System.in); //string object
      String dtString1 = "", dtString2 = "";

      System.out.print("Enter first date in dd/MM/yyyy format:");
      dtString1 = sc.nextLine();
      System.out.print("Enter second date in dd/MM/yyyy format:");
      dtString2 = sc.nextLine();

      //convert input date string into Date
      Date dt1 = dateF.parse(dtString1);
      Date dt2 = dateF.parse(dtString2);

      System.out.println("First Date is: " + dt1.toString());
      System.out.println("Second Date is: " + dt2.toString());

      if (dt1.after(dt2)) {
        System.out.println(dt1.toString() + " is greater than " + dt2.toString());
      } else if (dt1.before(dt2)) {
        System.out.println(dt1.toString() + " is less than " + dt2.toString());
      } else {
        System.out.println(dt1.toString() + " is equal to " + dt2.toString());
      }
    } catch (Exception e) {
      System.out.println("Exception is: " + e.toString());
    }
  }
}

Output

First Run:
Enter first date in dd/MM/yyyy format:21/08/2009
Enter second date in dd/MM/yyyy format:21/09/2008
First Date is: Fri Aug 21 00:00:00 IST 2009
Second Date is: Sun Sep 21 00:00:00 IST 2008
Fri Aug 21 00:00:00 IST 2009 is greater than Sun Sep 21 00:00:00 IST 2008

Second Run:
Enter first date in dd/MM/yyyy format:21/08/2008
Enter second date in dd/MM/yyyy format:21/08/2009
First Date is: Thu Aug 21 00:00:00 IST 2008
Second Date is: Fri Aug 21 00:00:00 IST 2009
Thu Aug 21 00:00:00 IST 2008 is less than Fri Aug 21 00:00:00 IST 2009

Third Run:
Enter first date in dd/MM/yyyy format:21/08/2008
Enter second date in dd/MM/yyyy format:21/08/2008
First Date is: Thu Aug 21 00:00:00 IST 2008
Second Date is: Thu Aug 21 00:00:00 IST 2008
Thu Aug 21 00:00:00 IST 2008 is equal to Thu Aug 21 00:00:00 IST 2008

Java Date and Time Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.