I need to do the CountDown Days
from one date to the second date
e.g
CURRENT_DATE:3/1/2013
NEXT_DATE:21/01/2013
then it displays ::17 DAYS LEFT
I implemented code like these
String inputDateString = "01/22/2013";
Calendar calCurr = Calendar.getInstance();
Calendar calNext = Calendar.getInstance();
calNext.setTime(new Date(inputDateString));
if(calNext.after(calCurr))
{
long timeDiff = calNext.getTimeInMillis() - calCurr.getTimeInMillis();
int daysLeft = (int) (timeDiff/DateUtils.DAY_IN_MILLIS);
dni.setText("Days Left: "+daysLeft);
}
else
{
long timeDiff = calCurr.getTimeInMillis() - calNext.getTimeInMillis();
timeDiff = DateUtils.YEAR_IN_MILLIS - timeDiff;
int daysLeft = (int) (timeDiff/DateUtils.DAY_IN_MILLIS);
}
Is there a better way to do achieve these?
Using Calendar
's Methods:
String inputDateString = "01/22/2013";
Calendar calCurr = Calendar.getInstance();
Calendar day = Calendar.getInstance();
day.setTime(new SimpleDateFormat("MM/dd/yyyy").parse(inputDateString));
if(day.after(calCurr)){
System.out.println("Days Left: " + (day.get(Calendar.DAY_OF_MONTH) -(calCurr.get(Calendar.DAY_OF_MONTH))) );
}
Output: Days Left: 17
And to increment the year by 1 , you could use Calendar.add() method
day.add(Calendar.YEAR, 1);
There are several libraries to convert date to n days
format:
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