看完了jdk的help,发现sun没有提供这样的一个函数,朋友给了几个实现方法
//取得剩余天数
SimpleDateFormat df=new SimpleDateFormat("yyyymmdd");
Date d0=new java.util.Date();
Date d1=df.parse(end_date);
long time0=d0.getTime();
long time1=d1.getTime();
System.out.println((time1-time0)/(1000*60*60*24));
这样算两个时间相差的天数比较好
/**
* 计算两个日期之间相差的天数
*
* @param date1
* @param date2
* @return
*/
public static int diffdates(Date date1, Date date2) {
int result = 0;
ElapsedTime et = new ElapsedTime();
GregorianCalendar gc1 = new GregorianCalendar();
GregorianCalendar gc2 = new GregorianCalendar();
gc1.setTime(date1);
gc2.setTime(date2);
result = et.getDays(gc1, gc2);
return result;
}
然后ElapseTime中的方法是:
public int getDays(GregorianCalendar g1, GregorianCalendar g2) {
int elapsed = 0;
GregorianCalendar gc1, gc2;
if (g2.after(g1)) {
gc2 = (GregorianCalendar) g2.clone();
gc1 = (GregorianCalendar) g1.clone();
} else {
gc2 = (GregorianCalendar) g1.clone();
gc1 = (GregorianCalendar) g2.clone();
}
gc1.clear(Calendar.MILLISECOND);
gc1.clear(Calendar.SECOND);
gc1.clear(Calendar.MINUTE);
gc1.clear(Calendar.HOUR_OF_DAY);
gc2.clear(Calendar.MILLISECOND);
gc2.clear(Calendar.SECOND);
gc2.clear(Calendar.MINUTE);
gc2.clear(Calendar.HOUR_OF_DAY);
while (gc1.before(gc2)) {
gc1.add(Calendar.DATE, 1);
elapsed++;
}
return elapsed;
}
其实使用joda最简单
public boolean isRentalOverdue(DateTime datetimeRented) {
Period rentalPeriod = Period.days(2);
return datetimeRented.plus(rentalPeriod).isBeforeNow()
}