首先,我们考虑了以下两个日期。
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = s.parse("2018-10-15"); Date d2 = s.parse("2018-11-10");
现在,使用该compareTo()
方法比较两个日期。根据返回值显示结果。
if (d1.compareTo(d2) > 0) { System.out.println("Date1 is after Date2!"); } else if (d1.compareTo(d2) < 0) { System.out.println("Date1 is before Date2!"); } else if (d1.compareTo(d2) == 0) { System.out.println("Date1 is equal to Date2!"); } else { System.out.println("How to get here?"); }
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Demo { public static void main(String[] args) throws ParseException { SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = s.parse("2018-10-15"); Date d2 = s.parse("2018-11-10"); if (d1.compareTo(d2) > 0) { System.out.println("Date1 is after Date2!"); } else if (d1.compareTo(d2) < 0) { System.out.println("Date1 is before Date2!"); } else if (d1.compareTo(d2) == 0) { System.out.println("Date1 is equal to Date2!"); } else { System.out.println("How to get here?"); } } }
输出结果
Date1 is before Date2!