Hãy thử chức năng này ...
function calculate_age(birth_month,birth_day,birth_year)
{
today_date = new Date();
today_year = today_date.getFullYear();
today_month = today_date.getMonth();
today_day = today_date.getDate();
age = today_year - birth_year;
if (today_month < (birth_month - 1))
{
age--;
}
if (((birth_month - 1) == today_month) && (today_day < birth_day))
{
age--;
}
return age;
}
HOẶC
function getAge(dateString)
{
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
{
age--;
}
return age;
}
See Demo.
Nguồn
2012-04-04 09:09:00
downvoted, vì nó là [tìm kiếm một cách dễ dàng] (https://duckduckgo.com/?q=get%20age%20from%20birth%20date%20javascript). Không thể nghĩ làm thế nào bạn nhận được rằng upvote! – halfer