Skip to content

Instantly share code, notes, and snippets.

@alphamu
Last active May 4, 2019 12:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alphamu/47c00a48630579b295e6 to your computer and use it in GitHub Desktop.
Save alphamu/47c00a48630579b295e6 to your computer and use it in GitHub Desktop.
Returns the difference between the provided date and now. The difference is in actual calendar days rather than time difference based. This means 01/Jan/2015 23:50 and 02/Jan/2015 00:01AM has a difference of 1 day.
/**
* Returns the difference between the provided date and now.
* The difference is in actual calendar days rather than time difference based.
* This means 01/Jan/2015 23:50 and 02/Jan/2015 00:01AM has a difference of 1 day.
*
* @param date The date from which the difference to today has to be calculated.
* @return difference in calendar days.
*/
public static int getRealDayDifference(Date date) {
String timeString = null;
Calendar now = Calendar.getInstance();
Calendar to = Calendar.getInstance();
to.setTime(date);
int daysDiff = now.get(DAY_OF_YEAR) - to.get(DAY_OF_YEAR);
//if negative, it's been over a year
if (daysDiff < 0) {
daysDiff += 365 + Math.abs(daysDiff);
}
//absolute value just in case the provided date is in the future.
int yearsDiff = Math.abs(now.get(YEAR) - to.get(YEAR));
int daysMultiplier = 0;
if (yearsDiff > 1) {
daysMultiplier = 365 * (yearsDiff - 1);
}
daysDiff += daysMultiplier;
return daysDiff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment