I am trying to implement something that can countdown how many days left before an event occurs. While dealing with days within the same year is fine. But now I am having a problem with showing a number of days which includes days that are not in the current year. For instance, if I input the target date as 1 January 2020 and current date as 30 September 2019. It will return -272 (days) which does not make any sense in general.
I have tried understanding and using code online but none of them worked for me.
What the code below does is to return a number of days left but only work when the days are within the same year. The labeledDate variable is a part of an inputted string (dateStamp) that shows only date that has the format of "dd MMMM yyyy".
// Show how many days left before event occurs
try {
String labeledDate = viewHolder.dateStamp.getText().toString().substring(5);
Calendar currentDay = Calendar.getInstance();
final Calendar targetDay = Calendar.getInstance();
SimpleDateFormat ourDateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.getDefault());
targetDay.setTime(ourDateFormat.parse(labeledDate));
if (targetDay.compareTo(currentDay) > 0) {
int daysLeft = targetDay.get(Calendar.DAY_OF_YEAR) - currentDay.get(Calendar.DAY_OF_YEAR);
if (daysLeft == 1) {
viewHolder.dayCounter.setText("Tomorrow");
}
else {
viewHolder.dayCounter.setText(daysLeft + " days");
}
}
else if (targetDay.compareTo(currentDay) == 0) {
viewHolder.dayCounter.setText("Today");
}
else {
viewHolder.dayCounter.setText("Expired");
}
} catch (ParseException e) {
Log.d("PARSE EXCEPTION", e.getMessage());
}
According to my current understanding of Calendar.DAY_OF_YEAR is that it consists of (maybe) 365 days. And if I enter the date 1st January 2020, it won't listen to the year whereas it will just focus on the day and month. Hence, if I entered the target date as 1st January 2020 and current date as 30th September 2019, then it would return -272 (days) from the day on 1st January minus the day on 30th September (years ignored).
What I want is that if I enter the inputs above then it will return 93 days instead of -272 days. Anything that can help me achieve this is appreciated.