10

I am trying to do calculate days between 2 dates as follow:

  1. Obtain current date
  2. Obtain past OR future date
  3. Calculate the difference between no. 1 and no. 2
  4. Present the dates in the following format
    • If the result is in past (2 day ago) or in the future (in 2 days)
    • Format will: days, weeks, months, years

I tried different ways but couldn't get the result I wanted above. I found out that Android DatePicker dialog box convert date into Integer. I have not found a way to make DatePicket widget to return date variables instead of integer.

private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, **int** year, 
                                  **int** monthOfYear, **int** dayOfMonth) {
                enteredYear = year;
                enteredMonth = monthOfYear;
                enteredDay = dayOfMonth;
            }
        };

I tried to convert the system date to Integer, based on the above, but this doesn't really work when trying to calculate days between 2 dates.

private void getSystemDate(){
     final Calendar c = Calendar.getInstance();

        mYear = c.get(Calendar.YEAR);
        systemYear = mYear;

        mMonth = c.get(Calendar.MONTH);
        systemMonth = mMonth + 1;

        mDay = c.get(Calendar.DAY_OF_MONTH);
        systemDay = mDay;

}
striders
  • 145
  • 1
  • 2
  • 8
  • ints aren't gonna work for calculating the difference between days. You'll need to use a long (like AedonEtLIRA said). – jahroy Apr 26 '12 at 03:37
  • That's the issue I am having - by default, the DatePicker in Android convert the date into integer, as the code snippet above shows. – striders Apr 27 '12 at 05:41
  • It doesn't immediately make sense to me how you could use an int to represent a date. Unless Android java is different, you can't represent a timestamp as an int because the max int value is not large enough. Timestamps are very large... like trillions and trillions. – jahroy Apr 27 '12 at 17:49
  • @jahroy - that's the default from Android. As you see from the 1st code above, when the a user set a date from the Date dialog picker, the DatePickerDialog.OnDateSetListener returns the value in integer. – striders May 22 '12 at 03:25
  • In your code, ints are used to represent the year, the month of the year, and the day of the month. It makes perfect sense to use ints for this... In fact it would make no sense to use longs for that. My comment (and all the answers below) suggest that you should determine the difference between two dates by subtracting the timestamps that represent those dates. That should be done with longs. Like these answers demonstrate, you need to determine the difference between the dates with timestamps, then convert the difference into days, weeks, months, etc... – jahroy May 22 '12 at 04:45
  • I guess the answer below uses ints for the difference, but that would cause problems if the dates were far apart. – jahroy May 22 '12 at 04:49
  • Based on my calculation, ints will only work for dates that are less than 25 days apart. – jahroy May 22 '12 at 05:05

3 Answers3

15
/** 
  *  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:

int year = delta / 365;
int rest = delta % 365;
int month = rest / 30;
rest = rest % 30;
int weeks = rest / 7;
int days = rest % 7;
Community
  • 1
  • 1
San
  • 5,567
  • 2
  • 26
  • 28
  • Thanks for the information! This will display the diff in days. What will be the appropriate ways to show this in days, weeks AND year? – striders Apr 26 '12 at 22:30
  • You need to do some math and use the modulo operator. To show x seconds as minutes and seconds, you would do this: int minutes = x / 60; int seconds = x % 60; String timeText = minutes + " min " + seconds + "sec"; The percentage sign is called the modulo operator. – jahroy Apr 27 '12 at 17:53
  • @striders Updated my answer... Please accept the answer if you think it is correct – San Apr 27 '12 at 19:23
  • Thank you for the revised answer on the weeks/days/months. I'll plug this in my Android code and will give it a shot! – striders May 19 '12 at 03:54
  • @striders - Using an int above will only work if your dates are less than 25 days apart. Edited the answer to use longs in stead. – jahroy May 22 '12 at 17:44
1
long delta = Date2.getTime() - Date1.getTime();

new Date(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.

ahodder
  • 11,353
  • 14
  • 71
  • 114
  • 1
    I think new Date(delta) wont work because the delta is not the milliseconds since January 1, 1970, 00:00:00 GMT. – San Apr 26 '12 at 04:50
1

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