如何比较时间的大小

时间的大小比较

1.Date的getTime方法,来获取时间,然后对两个时间进行比较。

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date oldDate1 = format.parse("2017-03-12 59:16:00"); 
Date oldDate2 = format.parse("2018-02-06 23:16:00");
if(d1.getTime() > d2.getTime()){
  return 1;   
}else if(d1.getTime() < d2.getTime()){
  return -1;
}else{
  return 0;
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date oldDate1 = format.parse("2017-03-12 59:16:00"); 
Date oldDate2 = format.parse("2018-02-06 23:16:00"); 
long day=num/(24*60*60*1000);
long hour=(num/(60*60*1000)-day*24);
long min=((num/(60*1000))-day*24*60-hour*60);
long s=(num/1000-day*24*60*60-hour*60*60-min*60);
System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");

2.Date中compareTo的用法。也是比较时间大小的,相等返回0,大于返回1,小于返回-1

       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
       Date oldDate1 = format.parse("2017-03-12 59:16:00"); 
       Date oldDate2 = format.parse("2018-02-06 23:16:00"); 
       System.out.println(oldDate1.compareTo(oldDate2)); 
原文地址:https://www.cnblogs.com/jodiegreat/p/6674137.html