可使用Date类中的compareTo()方法,该方法类似于BigDecimal种的compareTo()方法。
//定义两个date类型的变量,可以换成需要比较的字符串 SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date time=dateformat.parse("2020-7-14 14:18:00"); Date time1=dateformat.parse("2020-7-13 14:15:00"); System.err.println(time.compareTo(time1)); Date time2=dateformat.parse("2020-7-11 14:18:00"); Date times3=dateformat.parse("2020-7-13 14:15:00"); System.err.println(time2.compareTo(times3)); Date time4=dateformat.parse("2020-7-13 14:15:00"); Date times5=dateformat.parse("2020-7-13 14:15:00"); System.err.println(time4.compareTo(times5));如果time比time1大则输出1,相反若time1比time大则输出1。如果两个相等则输出0
计算时间类型(yyyy-MM-dd HH:mm:ss)时间差,类型可换成自己需要的。
long getDate = System.currentTimeMillis();//当前计算机时间 //将获取到的时间转成String类型 String dateStr = dateformat.format(getDate); //再转换成Date类型 Date time=dateformat.parse(dateStr); Date submitDate=dateformat.parse("String类型的时间"); //当前时间-String类型的时间 long los=time.getTime()-submitDate.getTime();submitDate的时间大于当前时间则结果为负数,计算出来的是毫秒 los/1000:秒 los/1000/60:分 los/1000/3600:小时
time比submitDate小,所以输出的是负数。 time比submitDate大,所以输出的是正数。 如果两个相等则输出0.