计算从2000月30日到现在经历了多少天?(提示:使用Calendar类,计算2000年5月30日到现在过去了多少毫秒,然后换算成天数)
1.毫秒算法
public static long getDays(Date small, Date big) {
if (small == null) {
return 0;
}
if (big == null) {
return 0;
}
long day = (big.getTime() - small.getTime()) / (24 * 60 * 60 * 1000);
return day;
}
2.可以使用java8的Instant
public static long toDays(Date startDate, Date endDate) {
Instant startDateInstant = startDate.toInstant();
Instant endDateInstant = endDate.toInstant();
return Duration.between(startDateInstant, endDateInstant).toDays();
}
先了解Calendar这个类,查看他的api,你会发现有很多方法,其中就有两者相差的天数和秒数