Ok, so I've created a function to show the number of days until a date in the future... It is correct until the amount of days is over 9 days.. if over it seems to show a random number of days... Please see my code below:
public String daysTillExpire() {
String daysLeft = "";
int position = 0 ;
String inputDateString = UIDM.get(position).date;
Calendar calCurr = Calendar.getInstance();
Calendar day = Calendar.getInstance();
try {
day.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(inputDateString));
} catch (ParseException e) {
e.printStackTrace();
}
if (day.after(calCurr)) {
String noumberOfDays = "Days left: " + (day.get(Calendar.DAY_OF_MONTH) - (calCurr.get(Calendar.DAY_OF_MONTH)));
daysLeft = UIDM.get(position).date + "\n(" + noumberOfDays+")" ;
}
else if (day.before(calCurr)) {
daysLeft = "Key Expired";
return daysLeft; }
return daysLeft;
}
UIDM
is a data model containing info... String inputDateString = UIDM.get(position).date;
returns the value 01-10-2018 23:59
.
Note that Calendar.DAY_OF_MONTH
returns the day of the month between 1 and 31
so it will calculate difference between two days (number between 1 and 31) as if they were in the same month
I would suggest to rather use timestamps and then convert the result from millis to number of days like this:
long oneDay = 24 * 60 * 60 * 1000; // in milliseconds
long diff = day.getTime().getTime() - calCurr.getTime().getTime();
long numberOfDays = diff / oneDay;
then you can change it to String
with Long.toString(numberOfDays)