I am trying to do calculate days between 2 dates as follow:
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;
}
The Period class has a between() method - just as the previously discussed ChronoUnit . This method takes in two LocalDate objects, one representing the starting date, and the second being the end date. It returns a Period consisting of the number of years, months, and days between two dates.
/**
* 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With