Compare date1 and date2 in java
If you want to compare two days together for the previous day, next day, or equal, you should use the compareTo function in java.
+ CompareTo() is method can be use to compare two days in java.
import java.util.Date; public class ExampleDate{ 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.
+ When you use method CompareTo two dates in java then function will for you produce with cause Before() and after() or equals() .
import java.util.Date; public class ExampleDate{ 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 } }