This Java program demonstrate to compare between two dates.
There are two completely different ways to comparing dates in Java.
- Compare date in milliseconds by using getTime() method.
- compareTo() method can be use to compare two dates in Java.
Example:
import java.util.Date;
public class DisplayDate {
public static void main(String args[]) {
// Instantiate a objects
Date date1 = new Date();
Date date2 = new Date();
if(date1.compareTo(date2)>0){
System.out.println("Date1 is after Date2");
}else if(date1.compareTo(date2)<0){
System.out.println("Date1 is before Date2");
}else{
System.out.println("Date1 is equal to Date2");
}
}
}
Program Output:
Date1 is equal to Date2
- before() and after() and equals() method is also used to compare dates.
Example:
import java.util.Date;
public class DisplayDate {
public static void main(String args[]) {
// Instantiate a objects
Date date1 = new Date();
Date date2 = new Date();
if(date1.before(date2)){
//Do Something
}
if(date1.after(date2)){
//Do Something
}
if(date1.equals(date2)){
//Do Something else
}
}
}
Explanation:
This Java program is used to compare between two dates. For comparing two dates, you have to write the program like this:
First you have imported the package java.util.Date; which contains all the pre defined methods that will deal with dates and time. The java.util.Date class is used to represent a precise moment in time having millisecond precision.
Now create a class with the name 'DisplayDate' inside which Date1 and Date2 are the objects of Date. Then implement a conditional statement if(date1.compareTo(date2)>0), which compares whether date1 is same as that of date2 and returns 0 if same and returns a value less than 0 when the argument is a string is lexicographically greater than this string; and returns a value greater than 0 when the argument is a string is lexicographically less than this string.
Now when the condition (date1.compareTo(date2)>0) is greater than 0, the program prints Date1 is after Date2", whereas when date1.compareTo(date2)<0, prints "Date1 is before Date2" and if both the dates are equal, prints the message - "Date1 is equal to Date2"