Age from Date of Birth using JQuery

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

    keep in mind that all above answers work only for date using separator '/'. if you are using other that this then you have to replace that separator first.

    var startDate = $('#start_date').val().replace('-','/');
    var endDate = $('#end_date').val().replace('-','/');
    
    if(startDate > endDate){
       // do stuff here...
    }
    

    happy coding :D

    0 讨论(0)
  • 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"
    )
    
    0 讨论(0)
  • 2020-11-30 07:16

    You could use the Date object. This will return the milliseconds between the two dates. There are 31556952000 milliseconds in a year.

    function dateDiff(var now, var dob)
    {
        return now.getTime() - dob.getTime();
    }
    
    0 讨论(0)
  • 2020-11-30 07:18
    Date.prototype.age=function(at){
        var value = new Date(this.getTime());
        var age = at.getFullYear() - value.getFullYear();
        value = value.setFullYear(at.getFullYear());
        if (at < value) --age;
        return age;
    };
    
    var dob = new Date(Date.parse($(this).text()));
    
    if(dob.age(new Date()) < 18)
    {
        $(this).text("Under 18");
    }
    else
    {
        $(this).text(" Over 18");
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 07:22

    My solution.

    var startDt=document.getElementById("startDateId").value;
    var endDt=document.getElementById("endDateId").value;
    if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
    {
        ----------------------------------  
    }
    
    0 讨论(0)
提交回复
热议问题