Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Age from Date of Birth using JQuery

Tags:

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 = Date.parse($(this).text());

if((curr-dob)<0)
{
    $(this).text("Under 18");
}
else
{
    $(this).text(" Over 18");
}

There must be some easier functions to use to compare dates rather than using the setFullYear and getFullYear methods.

Note: My actual reason for wanting to find a new method is length of the code. I have to fit this code into a database field that is limited to 250 chars. Changing the database is not something that can happen quickly or easily.

like image 257
Robin Day Avatar asked Mar 18 '09 14:03

Robin Day


People also ask

How to calculate age from Date of birth using jQuery?

You need to parse it into an actual number. dob = new Date(dob); var today = new Date(); var age = Math. floor((today-dob) / (365.25 * 24 * 60 * 60 * 1000)); $('#age'). html(age+' years old');

How do I calculate age in HTML?

function calculateAge(date) { const now = new Date(); const diff = Math. abs(now - date ); const age = Math. floor(diff / (1000 * 60 * 60 * 24 * 365)); return age } var picker = new Pikaday({ field: document.


2 Answers

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"
)
like image 179
Ken Browning Avatar answered Sep 21 '22 16:09

Ken Browning


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");
}
like image 39
David Avatar answered Sep 17 '22 16:09

David