Как посчитать возраст по дате рождения
Короткий ответ
Вычтите годы и отнимите ещё один, если в этом году день рождения ещё не наступил:
const getAge = (birth, today = new Date()) => {
let age = today.getFullYear() - birth.getFullYear();
const hadBirthday =
today.getMonth() > birth.getMonth() ||
(today.getMonth() === birth.getMonth() && today.getDate() >= birth.getDate());
if (!hadBirthday) age--;
return age;
};
console.log(getAge(new Date(1990, 5, 15), new Date(2025, 5, 14)));
console.log(getAge(new Date(1990, 5, 15), new Date(2025, 5, 15)));Результат:
34
35Из строки
Дата из формы приходит строкой вида 1995-12-01. Разделите её на числа и постройте локальную дату:
const [year, month, day] = '1995-12-01'.split('-').map(Number);
const birth = new Date(year, month - 1, day);
console.log(birth.toDateString());Результат:
Fri Dec 01 1995Частая ошибка
Деление разницы в миллисекундах на длину года даёт немного неверный возраст рядом с днём рождения из-за високосных лет:
const birth = new Date(2000, 2, 1);
const today = new Date(2025, 1, 28);
const years = (today - birth) / (365 * 24 * 60 * 60 * 1000);
console.log(Math.floor(years));Результат:
25Человеку ещё 24, а формула уже показывает 25.
Функции из этого ответа
- Date.prototype.getFullYear — Возвращает год.