Hàm tính tuổi từ ngày sinh trong JavaScript. | How to calculate age of person from date of birth using JavaScript?


Bài viết này cung cấp 2 hàm(function) JavaScript để tính tuổi của một người dựa vào thông tin ngày sinh của người đó.

Function 01:

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;
}


Function 02:

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;
}

*Chú thích
  • === : Ba dấu bằng được dùng để so sánh giá trị lẫn kiểu dữ liệu trong Javascript.
  • dateString : Bạn có thể ap dụng nhiều format được quy định khi tao biến date(yyyymmdd, yyyy-mm-dd, yyyy/mm/dd, mmddyyyy, mm-dd-yyyy, mm/dd/yyyy), nhưng nên tuân theo chuẩn định dạng(format) yyyymmdd cho dễ nhớ, dễ xử lý ^^!.



Write: +Bui Ngoc Son






No comments:

Post a Comment