Javascript: 檢查生日是否成年

接到一個開發需求,讓使用者填寫生日,然後用 Javascript 判斷是否滿二十歲。但是需要檢查到月和日… 總覺得有點懶。

Coding 發懶的時候,問 Stack Overflow 就對了….

function getAge(DOB) {
    var today = new Date();
    var birthDate = new Date(DOB);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

總之先修改一下,寫了一個草稿試試。結果如下:


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version