Last active
May 4, 2019 12:50
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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