views:

3391

answers:

5

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.

A: 

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(); }

Shaun Humphries
Surely there aren't that many milliseconds every year. Dates are hard.
Garry Shutler
that is not always true (leap years)
Jon Erickson
+1  A: 
$(this).text(((new Date().getFullYear()-Date.parts($(this).text()))>=18)?"Over 18":"Under 18");

Better? :D

Sudhir Jonathan
This only seems to use the year field for calculation, won't take into account months/days of current date and the DOB. So with this someone born in Dec 1991 would come back as over 18 in Jan 2009, which isn't true (they'd be 18 in Dec 2009).
Parrots
yes... it won't take into effect the months and days.. using a library would be useful if you want the full functionality, like in the first answer. Still can be built, though it might be difficult inside of 250 characters.
Sudhir Jonathan
A: 

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.

Parrots
+7  A: 

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"
)
Ken Browning
+1 - seems much easier to ready that others. I'm using this library and its been a big help.
RSolberg
+2  A: 
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");
}
Dave