有两个日期字符串,如:
String beginTime = new String("2021-10-01 10:22:33");String endTime = new String("2021-11-01 11:22:22");
需要比较两个日期的大小,有如下三种方法
1、Date自带 before( )和 after()方法比较
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date beginDate = df.parse(beginTime); Date endDate = df.parse(endTime); System.out.println(beginDate.before(endDate));//true System.out.println(beginDate.after(endDate));//false } catch (ParseException e) { e.printStackTrace(); }
2、String的compareTo()方法
返回正值代表左侧日期大于参数日期,反之亦然
注:日期格式必须一致
Integer integer = beginTime.compareTo(endTime); System.out.println(integer);//-1
3、将日期字符串 转成 Date格式,然后换成秒数比较秒数大小,getTime()方法
try { Date beginDate = df.parse(beginTime); Date endDate = df.parse(endTime); long longBegin = beginDate.getTime(); long longEnd = endDate.getTime(); System.out.println(longBegin);//1633054953000 System.out.println(longEnd);//1635736942000 } catch (ParseException e) { e.printStackTrace(); }
Date和String互转
//Date转String SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String ds = dateFormat.format(date); //String转Date String dateString = new String("2021-10-01 10:22:22"); try { Date date1 = dateFormat.parse(ds); } catch (ParseException e) { e.printStackTrace(); }
来源地址:https://blog.csdn.net/MinggeQingchun/article/details/121653740