Age from Date of Birth using JQuery

后端 未结 7 1682
轮回少年
轮回少年 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:19

    You can remove the separate variable for DOB and collapse the if statement. The below code comes in at 165 characters:

    var check = new Date();
    check.setFullYear(check.getFullYear() - 18);
    $(this).text((new Date("3/6/2009").getTime() - check.getTime() < 0)?"Under 18":"Over 18");
    

    This will still keep the logic needed to deal with leap-years.

提交回复
热议问题