总结:
after 只在大于(>)情况下才为true (相等时不会)
before 只在小于(<)情况下才为true (相等时不会)
compareTo
在两边相等(=)的情况下为 0
在左边大于(>)右边时为 1 (不区分大多长时间)
在左边小于(<)右边时为 -1 (不区分大多长时间)
compareTo
public class Demo2 { public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = sdf.parse("2000-01-00"); Date date2 = sdf.parse("2000-01-00"); System.out.println(sdf.format(date1)+"\tPK\t"+sdf.format(date2)+"\tresult:"+date1.compareTo(date2)); date1 = sdf.parse("2000-01-01"); date2 = sdf.parse("2000-01-00"); System.out.println(sdf.format(date1)+"\tPK\t"+sdf.format(date2)+"\tresult:"+date1.compareTo(date2)); date1 = sdf.parse("2000-01-00"); date2 = sdf.parse("2000-01-01"); System.out.println(sdf.format(date1)+"\tPK\t"+sdf.format(date2)+"\tresult:"+date1.compareTo(date2)); } }
运行结果:
after
public class Demo2 { public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = sdf.parse("2000-01-00"); Date date2 = sdf.parse("2000-01-00"); System.out.println(sdf.format(date1)+"\tPK\t"+sdf.format(date2)+"\tresult:"+date1.after(date2)); date1 = sdf.parse("2000-01-01"); date2 = sdf.parse("2000-01-00"); System.out.println(sdf.format(date1)+"\tPK\t"+sdf.format(date2)+"\tresult:"+date1.after(date2)); date1 = sdf.parse("2000-01-00"); date2 = sdf.parse("2000-01-01"); System.out.println(sdf.format(date1)+"\tPK\t"+sdf.format(date2)+"\tresult:"+date1.after(date2)); } }
运行结果:
before
public class Demo2 { public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = sdf.parse("2000-01-00"); Date date2 = sdf.parse("2000-01-00"); System.out.println(sdf.format(date1)+"\tPK\t"+sdf.format(date2)+"\tresult:"+date1.before(date2)); date1 = sdf.parse("2000-01-01"); date2 = sdf.parse("2000-01-00"); System.out.println(sdf.format(date1)+"\tPK\t"+sdf.format(date2)+"\tresult:"+date1.before(date2)); date1 = sdf.parse("2000-01-00"); date2 = sdf.parse("2000-01-01"); System.out.println(sdf.format(date1)+"\tPK\t"+sdf.format(date2)+"\tresult:"+date1.before(date2)); } }
运行结果: