Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Practice Object Interaction Checking Out and Returning a Book Demo: Charging Fines to Patrons

Mohamad Faiz Khairi Mohd Nazri
Mohamad Faiz Khairi Mohd Nazri
5,668 Points

My chargeFines method using for loops

chargeFines() {
    const dt = new Date;

    for (let i = 0; i < this.patrons.length; i++) {
      if (this.patrons[i].currentBook !== null && this.patrons[i].currentBook.dueDate < dt) {
        const dateDiff = new Date(dt - this.patrons[i].currentBook.dueDate);
        const daysLate = dateDiff.getDate();
        this.patrons[i].balance += (daysLate - 1) * this.dailyFine;
      }
    }
  }

Above is my way of writing the chargeFines method with for loops.

However, when i log the daysLate to the console, it give me 1 extra days and I don't know why. So my solution is I deduct the extra days through this code

this.patrons[i].balance += (daysLate - 1) * this.dailyFine;

Can somebody help me check my code. Thanks.

1 Answer

Steven Parker
Steven Parker
229,644 Points

Converting a time difference directly into a date isn't entirely legitimate. Using "getDate" on it is even less so, it will become extremely inaccurate for spans longer than a month.

To avoid inaccuracies in day difference calculations, you might consider these concepts:

  • always store or convert dates to UTC to avoid zone difference issues
  • if only whole day differences are desired, set hours/minutes/seconds/fractions to 0 on all dates
  • after subtracting dates, don't attempt to convert the result into a date
  • instead, just divide the result by the number of milliseconds in a day