This was a very tricky project and well done for completing it! I noticed that when I used your app with the date I put in (13 December 1990) the result was two years and 1 day higher than it should be, and I think I found a couple issues in your calcAge function:
Year Value
Where the currentMonth
value is less than the inputMonth
, currently you subtract 1 from inputYear
. You then subtract inputMonth
from currentMonth
and add 12, which would prevent you getting a negative number as a result. The issue is that in this instance you should add 1 to the inputYear
, not subtract one. When you add the 12 months, you're essentially adding 12 months to currentMonth
, which means you're kind of pretending as if today's date is 10/20/23 instead of 10/08/23 so you could subtract from it, and 10/20/23 would be in the future. This corrects the issue with the result being 2 years over. Admittedly it might need some more testing to make sure it works in more scenarios.
Month values
You generate the values for currentMonth
and inputMonth
differently, which causes some errors. For inputMonth
, you take the value in the months input box and cast it as a number, so December would be 12, as you would expect it to be. However for currentMonth
, you use the .getMonth()
method, which returns an index for the month of the Date
object it's used on. This means that August would return a 7, instead of an 8. As my inputDay
was larger than currentDay
, your calcAge
function subtracted 1 from inputDay
so the result was still correct, but if I put my inputDate
to 9 instead of 13, the result would be inaccurate by -1 month. Weirdly .getMonth()
is the only Date
method that returns an index, so this issue is very specific to this particular error.
There's also an issue that pops up for dates that are less than 1 month away, in that if I put 11/07/23 in, it says that that date is 1 Year, 1 Month and 30 days away - it's over by a month. I believe this is caused by the same issue that caused the Year Value issue (as you add 31 days where currentDay
is less than inputDay
but subtract 1 from inputMonth
) but there may also be some complexities arising from the different ways that currentMonth
and inputMonth
are generated.
Minor refactoring
You can also refactor your code a bit by changing let day = document.getElementById('inputDay')
into let day = document.getElementById('inputDay').value
and then using that in place of where you use inputDay
. You could also do the same for month and year.
There's also some minor inaccuracies I'm sure you're aware of which are due to the varying amount of days in a month, but these are quite tricky to fix without a package. I think you did a great job overall and most importantly - the frontend looks great!