Search code examples
androiddifferenceandroid-calendarandroid-date

Calculate difference between two calender dates in days


I know there are other similar questions have been asked here before, but as far as tried them none created the desired output, e.g. difference between 02.09.2016 and 30.08.2016 should be 3 calendar days.

    long diff = oldDate.getTime() - currentDate.getTime();
    long seconds = diff / 1000;
    long minutes = seconds / 60;
    long hours = minutes / 60;
    long days = hours / 24;

    int year = (int) diff / 365;
    int rest = (int) diff % 365;
    int month = rest / 30;
    rest = rest % 30;
    int weeks = rest / 7;
    int dayss = rest % 7;

    long diffMillis= Math.abs(oldDate.getTime() - currentDate.getTime());
    long differenceInDays = TimeUnit.DAYS.convert(diffMillis, TimeUnit.MILLISECONDS);

    Log.d("ASDafldsfg", "" + days);
    Log.d("ASDafldsfg", "" + dayss);
    Log.d("ASDafldsfg", "" + differenceInDays);

and the output is as following while calculating difference between 30.08.16 and 03.09.16

D/ASDafldsfg: 3
D/ASDafldsfg: 6
D/ASDafldsfg: 3

Solution

  • just casting double to float and then applying Math.ceil() fixed the problem,

    long diff = oldDate.getTime() - currentDate.getTime(); float days = (float) diff / 1000 / 60 / 60 / 24; tv_days.setText(String.valueOf((int) Math.ceil(days)));