0

I am trying to compare the current date with the date stored in the array, but I am not able to compare the date using if condition.

I use this code to compare the date:

DateFormat TO = new SimpleDateFormat("yyyy-MM-dd ");
Today = TO.format(Calendar.getInstance().getTime());
for (int i = 0; i < jsonArray.length(); i++) {

    // Today has a value 2018-03-13
    // ScheduleDates[i] has a value 2018-03-13
    // ScheduleDates[10] has a value 2018-03-13
    if (Today.equals(ScheduleDates[i])) {
        Toast.makeText(Main2Activity.this, "Match Found" + ScheduleDates[i] + "--"
                       + StartTimes[i] + "--" + Endtimes[i], Toast.LENGTH_LONG).show();
        break;
    } else {
        Toast.makeText(Main2Activity.this, "Match Not Found", Toast.LENGTH_LONG).show();
        break;
    }
}

But when I run the loop it shows only "match not found". I cannot find what error I had made, can anyone help to find the error?

diston
  • 129
  • 3
selva surya
  • 103
  • 9

2 Answers2

0

Use Log.d("Today",String.valueOf(Today)); to see what is in your Today variable. Also use

for(int i=0;i<jsonArray.length();i++){

   Log.d("Array",String.valueOf(ScheduleDates[i]));

}

Try to verify with your own eyes using the logcat that the exact date that is stored in your Today variable also exists in your array. If not, there is your problem. Your if statement works just fine, there just isn't any date in the array that is the same with the one in Today.

Edit: It is not visible in your code but i am willing to acept that jsonArray and ScheduleDates have the same length and that the second derives from the first. Otherwise your for loop would crash.

Edit2: Your problem actually is your break statements . Your for loop only runs once, so if the first item of the array matches the date in Today it stops and prints your success message. If the first item of your array does not match the date in Today it again stops and prints the failure message which is also the case as you have said.

So, remove the break statements and then the for loop will run as many times as it should and print the appropriate message whether it is for success or failure.

If you just want to find the first match and then stop, remove the break statement in your else but keep the one in your if.

0

only remove extra space define in date format like below ...

        DateFormat TO = new SimpleDateFormat("yyyy-MM-dd");