Please help me with the error that I'm doing wrong !!! It is necessary to calculate the number of full years. Somewhere I make a mistake.

var mydata = "2.1.1983"; function declOfNum(number, titles) { cases = [2, 0, 1, 1, 1, 2]; return number + " " + titles[(number % 100 > 4 && number % 100 < 20) ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]]; } function birthDateToAge(b) { var n = new Date(), b = new Date(b), age = n.getFullYear() - b.getFullYear(); return n.setFullYear(1970) < b.setFullYear(1970) ? age - 1 : age; } document.write(declOfNum(birthDateToAge(mydata), ['год', 'года', 'лет'])); 

Closed due to the fact that the participants are off-topic Igor , freim , LFC , Kromster , aleksandr barakin 4 Apr at 14:42 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - freim, Kromster
If the question can be reformulated according to the rules set out in the certificate , edit it .

2 answers 2

The error is that "2.1.1983" cannot be converted to a Date object, therefore bN b = new Date(b) leaves NaN .

It is necessary either to write the date in another format or otherwise transfer this format to the Date object (using the template you need the format).

Here is an example using a date in ISO format:

 var mydata = "1983-01-02"; // ISO function declOfNum(number, titles) { cases = [2, 0, 1, 1, 1, 2]; return number + " " + titles[(number % 100 > 4 && number % 100 < 20) ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]]; } function birthDateToAge(b) { var n = new Date(), b = new Date(b), age = n.getFullYear() - b.getFullYear(); return n.setFullYear(1970) < b.setFullYear(1970) ? age - 1 : age; } document.write(declOfNum(birthDateToAge(mydata), ['год', 'года', 'лет'])); 

    I subtract 1 from the difference between years, I add 1 if the birthday "this year was already" d is Date (), for example new Date (2000, 2, 4) - March 4, 2000

      function diff(d) { const now = new Date() const addOne = now.getMonth() - d.getMonth() >= 0 && now.getDate() - d.getDate() >=0 const diff = now.getFullYear() - d.getFullYear() return diff - 1 + (addOne ? 1 : 0) } 
    • now.getMonth() - d.getMonth() >= 0 && now.getDate() - d.getDate() >=0 - what is checked here? - Igor