My assignment at the university requires that we find how many days have passed from the current date to a user-defined birthday. The teacher asked to take into account leap years and that if the user enters a date from the future - I took that into account. Now we are asked to take into account the dates before 1900. I have been working with JS for just a couple of weeks and apparently I don’t know something, but as I don’t fight, it’s impossible. The exact answer to the question was not found. What should I read / look to solve this problem? What am I exactly doing wrong? Thank you very much for your attention!
function completeTask05() { const dayOfBirth = prompt("Enter your day of birth", "0"); const monthOfBirth = prompt("Enter your month of birth", "0"); const yearOfBirth = prompt("Enter your year of birth", "0"); const demo = document.body.getElementsByClassName("content-module__js-log")[0]; demo.innerHTML = "Im alive for " + countAge(dayOfBirth, monthOfBirth, yearOfBirth) + " days"; } function isLeapYear(year) { return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); } function countLYforwards(year) { console.log('future!'); let l = 0; for (let i = new Date().getFullYear(); i <= year; i++) { if (isLeapYear(i)) { l++; } } return l; } function countLYbackwards(year) { console.log('past!'); let l = 0; for (let i = new Date().getFullYear(); i >= year; i--) { if (isLeapYear(i)) { l++; } } return l; } function countLeapYears(year) { let l = 0; if (year > new Date().getFullYear()) { l = countLYforwards(year); } else { l = countLYbackwards(year); } return l; } function parseYear(year) { console.log('parsing ' + year); if (year.toString().length < 2) { console.log('!!!' + year); return '000' + year; } else if (year.toString().length < 3) { console.log('!!' + year); return "00" + year; } else if (year.toString().length < 4) { console.log('!' + year); return "0" + year; } return year.toString(); } function countAge(day, month, year) { const oneDay = (1000 * 60 * 60 * 24); const leapYears = countLeapYears(year); console.log(year.length); year.setFullYear(parseYear(year)); if (year > new Date().getFullYear()) { return Math.trunc((Math.abs(new Date() - new Date(year, month - 1, day)) + leapYears * oneDay) / oneDay); } else { return Math.trunc((Math.abs(new Date() - new Date(year, month - 1, day))) / oneDay); } }
(now.getTime() - past.getTime()) / (1000*60*60*24)- get the difference in days - Dmytryk