morristech
5/4/2019 - 12:50 PM

Returns the difference between the provided date and now. The difference is in actual calendar days rather than time difference based. This

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;
    }