调用CompareTo(Date anotherDate)方法,API如下:
public int compareTo(Date anotherDate)
String date1="2020-10-23";
String date2="2019-11-22";
//转换格式
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//[1]调用compareTo()方法
try {
Date date3=sdf.parse(date1);
Date date4=sdf.parse(date2);
switch(date3.compareTo(date4)) {
case 1:
System.out.println("大于");
break;
case 0:
System.out.println("相等");
break;
case -1:
System.out.println("小于");
break;
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
大于
通过getTime()方法的毫秒值判断
public long getTime()
String date1="2020-10-23";
String date2="2019-11-22";
//转换格式
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try {
Date date3=sdf.parse(date1);
Date date4=sdf.parse(date2);
long time1= date3.getTime();
long time2=date4.getTime();
System.out.println(time1+"\n"+time2);
System.out.println(time1>time2);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
1603382400000 1574352000000 true
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有