java获取日期之间天数的方法

时间:2021-12-09 22:20:38
//获取两个日期之间的天数
private int daysBetween(Date now, Date returnDate) {
Calendar cNow = Calendar.getInstance();
Calendar cReturnDate = Calendar.getInstance();
cNow.setTime(now);
cReturnDate.setTime(returnDate);
setTimeToMidnight(cNow);
setTimeToMidnight(cReturnDate);
long todayMs = cNow.getTimeInMillis();
long returnMs = cReturnDate.getTimeInMillis();
long intervalMs = todayMs - returnMs;
return millisecondsToDays(intervalMs);
}
//获取两个日期之间的分钟数
private int millisecondsToDays(long intervalMs) {
return (int) (intervalMs / (1000 * 86400));
}
//获取两个日期之间的毫秒数
private void setTimeToMidnight(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
}