views:

363

answers:

1

I'm trying to compare two datetimes but I can't get it to work.

    public void time () {
        Calendar c11 = Calendar.getInstance ();
        c11.add(Calendar.DAY_OF_YEAR, 0);
        c11.set(Calendar.HOUR_OF_DAY, 9);
        c11.set(Calendar.MINUTE, 0 );
        c11.set(Calendar.SECOND, 0);

        Calendar c12 = Calendar.getInstance ();
        c12.add(Calendar.DAY_OF_YEAR, 0);
        c12.set(Calendar.HOUR_OF_DAY, 9);
        c12.set(Calendar.MINUTE, 0 );
        c12.set(Calendar.SECOND, 0);

        c11.getTime();
        c12.getTime();
        boolean k = c11.equals(c12);
        if (k==true)
        {
            Toast.makeText(
              getContext(),
              "Wow these two times are the same!",
              Toast.LENGTH_LONG).show();
        }
    }
    }
+1  A: 
  1. The milliseconds of the 2 time values are different so the equality comparison is going to return false.

  2. Why are you adding 0 days to both calendar instances? That doesn't do anything.

mbaird
Why are the values different c11 and c12 are both set to be the same?
SamB09
No they are not the same. Like I just said, the milliseconds are different. You need to set the milliseconds to 0 on both of them. Right now the milliseconds are set to whatever the current time was when you called Calendar.getInstance()
mbaird
Right so is there anyother way i can compare these two ?
SamB09
Java Date and Calendar objects are always going to include milliseconds. You need to do the following: c11.set(Calendar.MILLISECOND, 0); c12.set(Calendar.MILLISECOND, 0); Then the equality comparison will return true.
mbaird
Ah great its working now thanks for your help.
SamB09