Android/Java - Date Difference in days

前端 未结 18 925
感动是毒
感动是毒 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:57

    Use the following functions:

       /**
         * Returns the number of days between two dates. The time part of the
         * days is ignored in this calculation, so 2007-01-01 13:00 and 2007-01-02 05:00
         * have one day inbetween.
         */
        public static long daysBetween(Date firstDate, Date secondDate) {
            // We only use the date part of the given dates
            long firstSeconds = truncateToDate(firstDate).getTime()/1000;
            long secondSeconds = truncateToDate(secondDate).getTime()/1000;
            // Just taking the difference of the millis.
            // These will not be exactly multiples of 24*60*60, since there
            // might be daylight saving time somewhere inbetween. However, we can
            // say that by adding a half day and rounding down afterwards, we always
            // get the full days.
            long difference = secondSeconds-firstSeconds;
            // Adding half a day
            if( difference >= 0 ) {
                difference += SECONDS_PER_DAY/2; // plus half a day in seconds
            } else {
                difference -= SECONDS_PER_DAY/2; // minus half a day in seconds
            }
            // Rounding down to days
            difference /= SECONDS_PER_DAY;
    
            return difference;
        }
    
        /**
         * Truncates a date to the date part alone.
         */
        @SuppressWarnings("deprecation")
        public static Date truncateToDate(Date d) {
            if( d instanceof java.sql.Date ) {
                return d; // java.sql.Date is already truncated to date. And raises an
                          // Exception if we try to set hours, minutes or seconds.
            }
            d = (Date)d.clone();
            d.setHours(0);
            d.setMinutes(0);
            d.setSeconds(0);
            d.setTime(((d.getTime()/1000)*1000));
            return d;
        }
    

提交回复
热议问题