Age from Date of Birth using JQuery

后端 未结 7 1655
轮回少年
轮回少年 2020-11-30 06:42

I need to calculate if someone is over 18 from their date of birth using JQuery.

var curr = new Date();
curr.setFullYear(curr.getFullYear() - 18);

var dob =         


        
7条回答
  •  时光取名叫无心
    2020-11-30 07:09

    You might find the open source Datejs library to be helpful. Specifically the the addYears function.

    var dob = Date.parse($(this).text());
    if (dob.addYears(18) < Date.today())
    {
        $(this).text("Under 18");
    }
    else
    {
        $(this).text(" Over 18");
    }
    

    In a more terse fashion:

    $(this).text(
        Date.parse($(this).text()).addYears(18) < Date.today() ?
        "Under 18" :
        " Over 18"
    )
    

提交回复
热议问题