For the most part, your project works. Close, but not quite.
There are 3 things I can recommend at this point.
First, your usage Date on the line let birthd = new Date...
is wrong. I would recommend reading into these docs on how to use Date methods, and look closely at their examples. Date is complicated and often confusing. Personally I use Dev Docs a lot, too, and it makes looking things up much easier.
Secondly, and this isn’t primarily your fault, it’s just how Date
works, time zones ruin your math. At some point, either when you’re defining today
or birthd
, a time zone is being attached automatically. It’s possibly even happening at both times.
For instance, you’re taking today’s date, let’s assume you just want 12/21/2020.
If I run new Date()
at this very moment, what I get is this:
Mon Dec 21 2020 18:09:35 GMT-0600 (Central Standard Time)
I don’t get just the day, the hours and so forth are also measured.
If I use new Date
to request the specific date of Dec 30th, 2010, I get:
Thu Dec 30 2010 00:00:00 GMT-0600 (Central Standard Time)
Doing the math you want to do may be easier if you convert your date objects to Unix date numbers with date.valueOf()
immediately, and then doing your math and diving seconds into years like you did. Also double check whatever date objects you are initially creating are in the same time zone before you start your calculations. Also, months in Date objects are zero-indexed, so January is 00, not 01.
Third, when I did get the “correct” answer, it was a floating number instead of an integer with many decimal points. Being xx.xxxxxxxxxxxxx years old isn’t usually an acceptable answer for most people.
Fourth, as a bonus, your code is offering me no restrictions for input. I could put 999999
in each of the 3 arguments and it would break your code.
In conclusion, Date can be a very powerful tool but it’s also very confusing and often inconsistent.