user623990
user623990

Reputation:

Method to compare dates doesn't seem to work -- at all

public void display(Date date) {
        for (int i = 0; i < this.position; i++) {
            schedule[i].init();
            while (schedule[i].hasMoreOccurrences()) {
                Date tmp = schedule[i].nextOccurrence();
                if (tmp.compareTo(date) == 0) {
                    System.out.println(schedule[i].toString());
                    schedule[i].init();
                    break;
                }

            }
        }
    }

Basically put, the above goes through an array of "events". Each event has a method to check is it has more occurrences and a method to get the next occurrence (which is of type date).

The method accepts a date and goes through the array and checks every event. For each event it checks if it has more occurrences. If it does, it checks if this occurrence is "equal" to the date specified. If it is, it prints the event and breaks out of the loop and moves to the next event in the array. If the next occurrence is not equal to the date given, it keeps checking as long as the event has more occurrences to check.

I know this method is SUPPOSED to print out events, however I'm getting no errors and no output. I've been playing around with it for a while to no avail.

I'm 100% sure my hasMoreOccurrences() and nextOccurrence() methods are working correctly because other parts of the code which relies on them heavily works.

I'm stumped :/ Thanks for the help :)

EDIT I've printed both tmp and date and I see that they both occur on the same DATE but not the same TIME. I don't care about the time, only about the date. Any ideas?

Upvotes: 4

Views: 2359

Answers (1)

BalusC
BalusC

Reputation: 1108712

There are several ways to compare two Date instances without taking the time into account.

  1. Convert both to Calendar and reset the fields of desinterest.

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    

    And then compare them.

    if (calendar1.equals(calendar2))
    

    (true, it's horrible, that's why JodaTime exist and JSR-310 is underway)

  2. Format to String without time and then parse back.

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    date = sdf.parse(sdf.format(date));
    

    And then compare them.

    if (date1.equals(date2))
    
  3. Use JodaTime from the beginning on.

    if (dateTime1.toLocalDate().equals(dateTime2.toLocalDate()))
    

Note that I used x.equals(y) instead of x.compareTo(y) == 0 because that's how you're supposed to compare objects on equality in Java.

Upvotes: 5

Related Questions