0

The Question:

"create a method called compare, which takes a parameter of type Date and calculates the number of days between the date of the current object and the input object."

public class Date {

    int year;
    int month;
    int day;

    void print() {
        System.out.printf("Date: %d/%d/%d", this.month, this.day, this.year);
    }

    void addDays(int n) {
        int[] month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        int i = this.month - 1;

        int day = this.day + n;

        while (day > month[i]) {

            day -= month[i];

            if (this.month == 12) {
                this.year++;
                this.month = 0;
                i = -1;
            }

            this.month++;
            i++;

        }
        this.day = 0;
        this.day += day;

    }

    int compare(Date d1) {

      return 0;
    }

}

This is what I currently have and I was wondering how would I implement this method I've tried messing around with the my method add days but I couldn't quite figure it out.

Again, I've tried messing around with addDays and adding parameter so that the method the object is calling must always be older than the one being compared but I get quite lost. Any advice would help.

msalaz03
  • 5
  • 2
  • 1
    The `java.time` package has all of this (and much more) for you; why on Earth would anyone ask you to reinvent that wheel? – E-Riz Jan 25 '23 at 19:02
  • @E-Riz University assignment :( – msalaz03 Jan 26 '23 at 18:04
  • Sadly, an outdated assignment. The `java.time` package has been around since Java 8, almost 9 years now. Maybe you can find a respectful way to point out to the instructor that the material is outdated and not necessarily preparing students for real-world work. – E-Riz Jan 26 '23 at 19:08

1 Answers1

0

you can refer to this post for complete explanation.

when you have two date objects simply subtract them:

long diff = date1.getTime() - date2.getTime();

and count the days:

TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
Reza
  • 54
  • 2