How to compare two string dates using the compareTo method?
package javaapplication;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JavaApplication {
public static void main(String args[]) {
String fromDateString = "2021-06-15";
String toDateString = "2021-07-15";
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date dateFrom = dateFormat.parse(fromDateString);
Date dateTo = dateFormat.parse(toDateString);
if (dateFrom.compareTo(dateTo) > 0) {
System.out.println("From Date is greater than To Date");
} else if (dateFrom.compareTo(dateTo) < 0) {
System.out.println("From Date is less than To Date");
} else if (dateFrom.compareTo(dateTo) == 0) {
System.out.println("From Date is Equal to To Date");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}