原因是夏令时间会造成计算错误,差一小时就是差一天,用毫秒数计算已经不是正确方法了。
现代标准就是尽量不要使用毫秒数计算日期。
以下是正确方法:
public long daysBetween(Date start,Date end){
long diff = 0;
if (start == null || end == null) {
return diff;
}
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
try {
start = f.parse(f.format(start));
end = f.parse(f.format(end));
} catch (ParseException e) {
return diff;
}
Calendar c = Calendar.getInstance();
if(start.before(end)){
c.setTime(start);
while (c.getTime().before(end)) {
c.add(Calendar.DAY_OF_MONTH, 1);
diff++;
}
}else{
c.setTime(start);
while (c.getTime().after(end)) {
c.add(Calendar.DAY_OF_MONTH, -1);
diff--;
}
}
return diff;
}