Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android days left

Tags:

java

android

time

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?

like image 824
Radek.Dev Avatar asked Jan 04 '13 11:01

Radek.Dev


2 Answers

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);
like image 136
PermGenError Avatar answered Sep 19 '22 13:09

PermGenError


There are several libraries to convert date to n days format:

  • PrettyTime
  • JodaTime
like image 31
hsz Avatar answered Sep 22 '22 13:09

hsz