Calendar implementation: trouble to add days to date

i_want_to_code :

My task is: Implement the method public void advance() that moves the date by one day. In this exercise we assume that each month has 30 day. NB! In certain situations you need to change the values of month and year.

I have done this:

public class SimpleDate {

    private int day;
    private int month;
    private int year;

    public SimpleDate(int day, int month, int year) {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    @Override
    public String toString() {
        return this.day + "." + this.month + "." + this.year;
    }

    public boolean before(SimpleDate compared) {
        if (this.year < compared.year) {
            return true;
        }

        if (this.year == compared.year && this.month < compared.month) {
            return true;
        }

        if (this.year == compared.year && this.month == compared.month &&
                 this.day < compared.day) {
            return true;
        }

        return false;
    }

    public void advance(){
        if(this.day<30){
            this.day += 1;
        }    
        if(this.day==30 && this.month==12){
            this.day = 1;
            this.month=1;
            this.year +=1;
        }
        if(this.day==30){
            this.day = 1;
            this.month +=1;
        }
    }

    public void advance(int howManyDays){
        if(howManyDays < 30){
            if(this.day<30 && (this.day + howManyDays < 30)){
                this.day += howManyDays;
            }
            if(this.day==30 && this.month==12){
                this.day = howManyDays;
                advance();
            }
            if(this.day==30){
                this.day = howManyDays;
                this.month +=1;
            } 
        }
        if(howManyDays== 30 && this.month==12){
            this.day = howManyDays;
            advance();
        }
        if(howManyDays == 30){
            this.month += 1;
        }
    }
    public SimpleDate afterNumberOfDays(int days){

        SimpleDate obj = new SimpleDate(days, this.month,this.year);
        return obj;

    }

}

But when I test it with:

SimpleDate date = new SimpleDate(30, 12, 2011);  date.advance(3);

Now the date should be 3.1.2012. expected:[3.1.2012] but was:[4.12.2011]

Tim Hunter :

I recommend just simplifying your approach on this with while loops instead of the multiple and nested if statements...

public void advance(int howManyDays) {
  this.day += howManyDays;

  //Subtracts out the days till within range, incrementing months
  while(this.day > 30) {
    this.day -= 30;
    this.month++;
  }

  //Subtracts out the months till within range, incrementing years
  while(this.month > 12) {
    this.month -= 12;
    this.year++;
  }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=396335&siteId=1