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 Solution: Charging Fines to Patrons

Farid Lavizadeh
Farid Lavizadeh
12,006 Points

DayLate can't be correct.

const daysLate = dateDiff.getDate() in the code will always gets a day of a month, not total number of days. While this works if the number of days is less than 30 days, I don't see h it would work for someone who is, say, 100 days late. I keep trying this in the console and I can never get the correct answer.

Mark Westerweel
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Mark Westerweel
Full Stack JavaScript Techdegree Graduate 22,378 Points

True, tried it over here as well. In this way you get a discount for returning later than a month, lol.

We can use the two dates and add a getTime() method to find out the difference in TIME. We can convert that to amount of days and work our way from there.

Here's a link to the concept

3 Answers

I saw the same problem... solved it with simple date math. I was working from the books perspective not the patrons perspective but the logic is the same.

const todayDate = new Date(); const fine = (this.books[x].dueDate.getDate() - todayDate.getDate()) * this.dailyFine;

Yes, that is correct.

Using getTime() will be the most accurate. The following is my solution

  const today = new Date()
  const msLapse = today.getTime() - book.dueDate.getTime()
  const dayLapse = msLapse / 86400000 // 1 day = 86.400.000 ms

  // now charge the fine
  book.patron.balance += dayLapse * this.dailyFine

Yeah, this is definitely a bug.

Put together this stand-alone test based on the course's solution, so anyone can try it out in their console.

let date = new Date('1-1-2021');
let lateDate = new Date();
lateDate.setDate(lateDate.getDate() - 100); // 100 days late
const dateDiff = new Date(date - lateDate);
const daysLate = dateDiff.getDate();
console.log(daysLate); // result: 17 days late - INCORRECT

This produces a result of 17 days late, even though I hard-coded 100 days late. This is because the .getDate method of Date returns the day of the month (1-31 depending on the month). So the math ends up being all wrong because it will never return a number over 31.