Java method to get the number of days between dates
- 2020-04-01 04:03:31
- OfStack
This article illustrates how Java gets the number of days between dates. Share with you for your reference. The specific implementation method is as follows:
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);
}
I hope this article has been helpful to your Java programming.