Find difference in days in Java
To calculate the difference between two dates, we will be using Calendar (java.util.*)
public static long daysDifference(Calendar startDate, Calendar endDate)
{
Calendar date = (Calendar) startDate.clone();
long daysBetween = 0;
while (date.before(endDate))
{
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
The while loop will be executed until the startDate is less than the endDate. The long value daysBetween will return the days difference.
public static long daysDifference(Calendar startDate, Calendar endDate)
{
Calendar date = (Calendar) startDate.clone();
long daysBetween = 0;
while (date.before(endDate))
{
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
The while loop will be executed until the startDate is less than the endDate. The long value daysBetween will return the days difference.
Comments
Post a Comment