In this section we will do step by step
1. Comparator Date in Java
2. Comparator by using method after(), before() and equal()
public boolean after(Date date);
public boolean before(Date date)
public boolean equal(Object o);
See Example1;
import java.util.Date;
public class Details {
public static void main(String[] args) {
Date today = new Date();
Date myDate = new Date(today.getYear(),today.getMonth()-1,today.getDay());
getCompareDate(today, myDate);
}
public static void getCompareDate(Date today, Date myDate){
System.out.println("method Comparator > My Date is : "+myDate);
System.out.println("method Comparator Today Date is : "+today);
if (today.compareTo(myDate)<0){
System.out.println(" method Comparator Today Date is Lesser than my Date");
}
else if (today.compareTo(myDate)>0){
System.out.println(" method Comparator Today Date is Greater than my date");
}
else{
System.out.println("Both Dates are equal");
}
}
//result:
method Comparator > My Date is : Mon Feb 01 00:00:00 ICT 2016
method Comparator Today Date is : Mon Mar 14 23:52:02 ICT 2016
method Comparator Today Date is Greater than my date
Example2: method after(), before(), equal();
import java.util.Date;
public class Details {
public static void main(String[] args) {
Date today = new Date();
Date myDate = new Date(today.getYear(),today.getMonth()-1,today.getDay());
getDateComapreBeforeAndAfter(today, myDate);
}
private static void getDateComapreBeforeAndAfter(Date today, Date myDate){
//After() or before() or equal() method want to know today > myDate ? and it return boolean true or false
System.out.println("Date method compare Before : "+today.before(myDate));
System.out.println("Date method compare After : "+today.after(myDate));
System.out.println("Date method compare equal : "+today.equals(myDate));
}
}
result :
Date method compare Before : false
Date method compare After : true
Date method compare equal : false
EmoticonEmoticon