1

I am quite new to Android development, but the person has written the code is away and i have taken over this job.

There is one thing I would like to find out quickly...(--

The app is picking up the user input of a date (using a date picker) and i need add a validation to check the if the date is valid. The valid dates are 30 days from today. After searching on the internet for long time, i've found a code i might can use:

  Date today = new Date();
  Date predefined = new SimpleDateFormat("yyyy-MM-dd").parse(today);

  if(today.before(predefined)) {
      ...
  }

But I am not sure how to add 30 days?

If you could tell me, that would be much appreciated. Thanks in advance.

Edit Here is the Source code I've tried.

Calendar today = Calendar.getInstance();
today.add(Calendar.DAY_OF_MONTH,30);
if(calStartDate.compareTo(today)<0) { 
    Toast.makeText(GetClient.this,"It's before valid date!",Toast.LENGTH_SHORT).show();
}else{ 
    Toast.makeText(GetClient.this,"It's a valid date!",Toast.LENGTH_SHORT).show();
}
FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
user973067
  • 327
  • 2
  • 10
  • 20
  • 1
    this answers can help you: http://stackoverflow.com/questions/3838527/android-java-date-difference-in-days – jamapag Oct 20 '11 at 23:49

2 Answers2

4

You want the Calendar class. You can create one and set it to current time/date, and create another and set roll it forward 30 days. Then call compareTo() on one passing in the other.

FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
  • Hi, thanks for your comment. based on that i've done it live this: Calendar today = Calendar.getInstance(); today.add(Calendar.DAY_OF_MONTH,30); if(calStartDate.compareTo(today)<0) { Toast.makeText(GetClient.this,"It's before valid date!",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(GetClient.this,"It's a valid date!",Toast.LENGTH_SHORT).show(); } but still not working. i'm sorry for the mess – user973067 Oct 21 '11 at 10:44
  • Is the range of valid dates from the current day to 30 days in the future? Or are they allowed to enter dates before the current day? – FoamyGuy Oct 21 '11 at 13:28
4

Implement this logic in ur OnDateSetListener:::

     class DateListner implements OnDateSetListener
{

    @Override
    public void onDateSet ( DatePicker view , int year , int monthOfYear ,
            int dayOfMonth )
    {
        Date inputDate = new Date(year, monthOfYear, dayOfMonth);
        Long inputTime = inputDate.getTime();
        Calendar calendar=Calendar.getInstance();
        Date validDate = new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), (calendar.get(Calendar.DAY_OF_MONTH)+30));
        Long validTime = validDate.getTime();
        if(validTime>inputTime){
            Log.e("result", "valid");
        }
        else
            Log.e("result", "invalid");
    }
}

Cheers......!!!!

Rohit
  • 593
  • 2
  • 8