Search code examples
javadatewhile-loopgregorian-calendar

How to Count Number of Days Between Two Dates Using the Gregorian Calendar and While Loops


public class DVD implements Serializable {

private static final long serialVersionUID = 1L;
protected GregorianCalendar rentedOn;
protected GregorianCalendar dueBack;
protected String title;
protected String nameOfRenter;

public double getCost(GregorianCalendar ActualDatRented) {
    double cost = 3;
    double count = 0;
    if (ActualDatRented.after(this.dueBack)) {
        while(!dueBack.equals(ActualDatRented)) {
            count++;
            dueBack.add(Calendar.DATE,1);
            cost = cost + count;
            return cost;
        }
    }else if(ActualDatRented.equals(dueBack))
        cost = 3;

    return cost;
  }
}

This code is suppose to calculate the number of days between the dueBack and ActualDatRented and increase the cost by $1 for every day past the dueBack date. It doesn't need to be in a while loop but I thought it would be easier to write, but I do know that if written in a while loop it will have to loop through each day until the ActualDatRented is equal to the dueBack date and add the 1 to cost each loop. How do I make this code work?


Solution

  • To answer your question, the reason why your code stops after one loop is the return statement at the end of the while loop. Also, if dueBack is the same as ActualDateRented, it will return 3, as per your else statement.

    But there's a few other things wrong with this code. You're comparing dueBack with ActualDateRented by using !=, which for objects checks if they are both the exactly the same object, instead of comparing values. You should use the equals method to compare the dates.

    In a more general sense, is there a particular reason why you're using GregorianCalendar instead of Java 8's Date/Time API? The 'new' API is a lot easier to use, and you don't need to write your own loops to determine the difference between days. You could check https://www.baeldung.com/java-8-date-time-intro for more info.