Dates Not Matching

I have a TreeMap of <DDate, Integer>.

DDate just contains month and year (month is 0 indexed, like in Java, JAN = 0);

My compare is not returning the right thing:

@Override
public int compareTo(DDDate o) {

    Calendar cal1 = Calendar.getInstance();
    cal1.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal1.set(year, month, 1); // year is 2012, month is 1

    Calendar cal2 = Calendar.getInstance();
    cal2.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal2.set(o.getYear(), o.getMonth(), 1); // year is 2012, month is 1


    Log.log("COMPARING: " + format.format(cal1.getTime())); // COMPARING: 20120101
    Log.log("COMPARING: " + format.format(cal2.getTime())); // COMPARING: 20120101

    Log.log((cal1.getTime().getTime())); // 1325413927678
    Log.log((cal2.getTime().getTime())); // 1325413927679

    Log.log("WILL RETURN: " + cal1.getTime().compareTo(cal2.getTime())); // WILL RETURN: -1

    return cal1.getTime().compareTo(cal2.getTime());

}

Why is there descrepancy in the two Calendar objects for the same Date? (1325413927678 vs 1325413927679)

Thank you!

FYI: this method works for a while, and then at a certain point, stops working.

P.S. - I understand this is overkill, I can have a simpler compareTo, but please humor me.

EDIT- FIX

Use JodaTime's LocalDate.

Or do this:

Calendar cal1 = Calendar.getInstance();
cal1.setTimeZone(TimeZone.getTimeZone("UTC"));
cal1.clear();
cal1.set(year, month, 1); // year is 2012, month is 1
Jon Skeet
people
quotationmark

You're setting the year, month and day - but that doesn't change the time of day. The internal clock must have ticked between the two calls to Calendar.getInstance, so they have different "milliseconds since the Unix epoch" values.

Personally I'd recommend using Joda Time instead of java.util.Calendar and java.util.Date - that way you can represent what you're actually interested in, such as LocalDate.

people

See more on this question at Stackoverflow