user3339562
user3339562

Reputation: 1385

Calendar getTimeInMillis() returns same value after changing hours and minutes

The problem occurs in the following scenario:

public void setCal(final Calendar calendar) {
  Calendar c1 = pickedDate;
  Calendar c2 = pickedDate;

  Log.d(TAG, c1.getTimeInMillis());
  Log.d(TAG, c2.getTimeInMillis());

  c1.set(Calendar.HOUR_OF_DAY, 10);
  c1.set(Calendar.MINUTE, 20);

  c2.set(Calendar.HOUR_OF_DAY, 18);
  c2.set(Calendar.MINUTE, 30);

  Log.d(TAG, c1.getTimeInMillis());
  Log.d(TAG, c2.getTimeInMillis());
}

After I compare values with getTimeInMillis() before and after calling set() method to both calendars, I notice they are the same. Any idea why is this happening?

Upvotes: 0

Views: 282

Answers (1)

dryairship
dryairship

Reputation: 6077

This is because here:

Calendar c1 = pickedDate;
Calendar c2 = pickedDate;

You set both objects to pickedDate. So any change in any object will change the values in pickedDate, which is actually, both the instances c1 and c2. One way to tackle this is changing those lines to:

Calendar c1 = (Calendar)pickedDate.clone();
Calendar c2 = (Calendar)pickedDate.clone();

This will set them to clones of pickedDate, ie, they will not be the same.

Upvotes: 5

Related Questions