-3

The idea was to calculate the number of days in a year from a specific date taking into account leap years. The expected result was either 365 or 366. In practice I got one day more than expected.

This what I tried I expected to get 366 here, given that 2024 is a leap year.

let startDate = new Date(); 
console.log(startDate)
// Reset to start from 00:00:00
startDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate()); 
console.log(startDate)
let endDate = new Date(startDate.getFullYear()+1, startDate.getMonth(), startDate.getDate()); 
console.log(endDate)
console.log((endDate - startDate)/(1000*60*60*24)) // 366
  • 3
    The question has already been closed, but your issue comes from using `Date.getDay()` instead of `Day.getDate()`. You were returning the day of the week - e.g. Monday is 1, Tuesday is 2 etc. So when you change the year that number changes and you get the result wrong. – Nick Aug 22 '23 at 09:17
  • Notice that your end date is 2nd August, not the 1st! – phuzi Aug 22 '23 at 09:18
  • @phuzi Thanks for your reply. You're right, after I substituted getDate for getDay it worked as expected. – Tony Patrinos Aug 22 '23 at 10:09

0 Answers0