Q:

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

belongs to collection: Java Date and Time Programs

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Date and Time Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to convert Date string to Date format in Java?... >>