Design comparison
Solution retrospective
Sometimes i dont get the proper date and when i refresh it and run again , it comes proper. I dont know why it happens, I still guess there is needed more improvement to my present code, need some suggestions
Community feedback
- @LeonardoR3DPosted over 1 year ago
Hello, first of all congratulations for completing the challenge, but I suggest you retake it from here to fix the error you are talking about, for that let me give you some tips.
First, the error that causes the date to sometimes not calculate correctly happens because of this code that is in line 58 of your javascript file
if (inputDay > day) { day += months[month - 1]; month -= 1; } if (inputMonth > month) { month += 12; year -= 1; }
The problem here is that you are changing the value of the variables that contain your current date, so the first calculation that executes these conditions is correct, but the following calculations will be wrong.
For example, today is March 23, 2023, which makes your variables look like this
day = 23
month = 5
year = 2023
and if you enter this date into the calculator "DAY = 30" "MONTH = 7" "YEAR = 2000" the result will be correct, but now your variables look like thisday = 54
month = 16
year = 2022
and after that if you try to calculate another date the result will be incorrect.One way to solve this could be to declare new variables at the beginning of your function and use them for the calculation, this way you make sure that the calculation always starts with the correct date, an example of this would be the following.
function handleSubmit(e) { e.preventDefault(); if (validate()) { const inputDay = parseInt(dayInp.value); const inputMonth = parseInt(monthInp.value); const inputYear = parseInt(yearInp.value); let calcDay = day; let calcMonth = month; let calcYear = year; if (inputDay > day) { calcDay += months[month - 1]; calcMonth -= 1; } if (inputMonth > month) { calcMonth += 12; calcYear -= 1; } const d = calcDay - inputDay; const m = calcMonth - inputMonth; const y = calcYear - inputYear; dayOtp.innerHTML = d; monthOtp.innerHTML = m; yearOtp.innerHTML = y; } }
I hope all this has been helpful, good day and good luck ;D.
0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord