Skip to content Skip to sidebar Skip to footer

(java / Android) Calculate Days Between 2 Dates And Present The Result In A Specific Format

I am trying to do calculate days between 2 dates as follow: Obtain current date Obtain past OR future date Calculate the difference between no. 1 and no. 2 Present the dates in th

Solution 1:

/** 
  *  Returns a string that describes the number of days
  *  between dateOne and dateTwo.  
  *
  */public String getDateDiffString(Date dateOne, Date dateTwo){
    long timeOne = dateOne.getTime();
    long timeTwo = dateTwo.getTime();
    long oneDay = 1000 * 60 * 60 * 24;
    long delta = (timeTwo - timeOne) / oneDay;

    if (delta > 0) {
        return"dateTwo is " + delta + " days after dateOne";
    }
    else {
        delta *= -1;
        return"dateTwo is " + delta + " days before dateOne";
    }
}

Edit: Just saw the same question in another thread: how to calculate difference between two dates using java

Edit2: To get Year/Month/Week, do something like this:

intyear= delta /365;
int rest = delta %365;
intmonth= rest /30;
rest = rest %30;
int weeks = rest /7;
int days = rest %7;

Solution 2:

long delta = Date2.getTime() - Date1.getTime();

newDate(delta);

From here, you just pick your format. Maybe use a date formatter? As for determing the future stuff and all that, you could just see if the delta is positive or negative. A negative delta will indicate a past event.

Solution 3:

Well, java/android API has all answers for you:

    Calendar myBirthday=Calendar.getInstance();
    myBirthday.set(1980, Calendar.MARCH, 22);
    Calendar now = Calendar.getInstance();
    long diffMillis= Math.abs(now.getTimeInMillis()-myBirthday.getTimeInMillis());
    long differenceInDays = TimeUnit.DAYS.convert(diffMillis, TimeUnit.MILLISECONDS);

Post a Comment for "(java / Android) Calculate Days Between 2 Dates And Present The Result In A Specific Format"