Android/Java - Date Difference in days

前端 未结 18 923
感动是毒
感动是毒 2020-11-22 14:17

I am getting the current date (in format 12/31/1999 i.e. mm/dd/yyyy) as using the below code:

Textview txtViewData;
txtViewDate.setText(\"Today is \" +
              


        
18条回答
  •  情话喂你
    2020-11-22 14:35

    All of these solutions suffer from one of two problems. Either the solution isn't perfectly accurate due to rounding errors, leap days and seconds, etc. or you end up looping over the number of days in between your two unknown dates.

    This solution solves the first problem, and improves the second by a factor of roughly 365, better if you know what your max range is.

    /**
     * @param thisDate
     * @param thatDate
     * @param maxDays
     *            set to -1 to not set a max
     * @returns number of days covered between thisDate and thatDate, inclusive, i.e., counting both
     *          thisDate and thatDate as an entire day. Will short out if the number of days exceeds
     *          or meets maxDays
     */
    public static int daysCoveredByDates(Date thisDate, Date thatDate, int maxDays) {
        //Check inputs
        if (thisDate == null || thatDate == null) {
            return -1;
        }
    
        //Set calendar objects
        Calendar startCal = Calendar.getInstance();
        Calendar endCal = Calendar.getInstance();
        if (thisDate.before(thatDate)) {
            startCal.setTime(thisDate);
            endCal.setTime(thatDate);
        }
        else {
            startCal.setTime(thatDate);
            endCal.setTime(thisDate);
        }
    
        //Get years and dates of our times.
        int startYear = startCal.get(Calendar.YEAR);
        int endYear = endCal.get(Calendar.YEAR);
        int startDay = startCal.get(Calendar.DAY_OF_YEAR);
        int endDay = endCal.get(Calendar.DAY_OF_YEAR);
    
        //Calculate the number of days between dates.  Add up each year going by until we catch up to endDate.
        while (startYear < endYear && maxDays >= 0 && endDay - startDay + 1 < maxDays) {
            endDay += startCal.getActualMaximum(Calendar.DAY_OF_YEAR); //adds the number of days in the year startDate is currently in
            ++startYear;
            startCal.set(Calendar.YEAR, startYear); //reup the year
        }
        int days = endDay - startDay + 1;
    
        //Honor the maximum, if set
        if (maxDays >= 0) {
            days = Math.min(days, maxDays);
        }
        return days;
    }
    

    If you need days between dates (uninclusive of the latter date), just get rid of the + 1 when you see endDay - startDay + 1.

提交回复
热议问题