Abish R
Abish R

Reputation: 1567

Calender Date Difference Calculation error in Android

I know there are many formats of example to calculate the two dates difference. I tried in a way from that one. My answer is always correct if I input the dates within a single month. If I go for finding difference more than a month it was not giving correct answer. It was always finding the difference for two dates. How can I find date difference more that 31 days or 2016-01-05 to 2015-12-13.

Date oldDate,newDate;
SimpleDateFormat dateFormat;

//editText1=2015-12-13
//editText2=2016-01-05

oldDate = dateFormat.parse(editText1.getText().toString());
newDate = dateFormat.parse(editText2.getText().toString());
oldDate=dateFormat.parse(dateFormat.format(oldDate));
newDate=dateFormat.parse(dateFormat.format(newDate));
long diff = newDate1.getDate() - oldDate1.getDate();
editText3.setText(""+(diff+1));

Upvotes: 0

Views: 70

Answers (1)

Karakuri
Karakuri

Reputation: 38605

Convert the dates to timestamps in milliseconds, subtract one from the other, and divide the result by 86400000 (milliseconds in a day).

long oldTime, newTime;
oldTime = dateFormat.parse(editText1.getText().toString()).getTime();
newTime = dateFormat.parse(editText2.getText().toString()).getTime();
long daysDiff = Math.abs(newTime - oldTime) / DateUtils.DAY_IN_MILLIS;

Upvotes: 1

Related Questions