Reputation: 10745
HI,
I have the following code that is supposed to compare two dates:
var d = ($('#day').val());
var m = ($('#month').val() -1);
var y = $('#year').val();
var birthdate = new Date(y,m,d);
alert('birthdate is' + birthdate);
var today = new Date();
alert('today is'+ today);
var diff = (today - birthdate);
years = Math.floor(diff/(1000*60*60*24*365));
alert(years);
It's basically working but I'm interested to see if the date of birth makes the user over 18 or not. So I've tried to put in 30th march 1993 - which would make the user 17. I'm alerting out the birthdate and it gives me back the correct date (mon mar 29 1993 00:00:00 GMT + 0100 BST)....however this is evaluating to 18 (alert(years) in the above code) when it should evaluate to seventeen. It's not until I put in 3rd April 1993 that it evaluates to 17.
Any ideas?
Upvotes: 0
Views: 295
Reputation: 16846
That's because you forgot the leap years.
These years had 366 days and occur usually every four years, so in any 18 years there are about four days more than 365*18, thus moving the neccessary start date four days ahead.
Probably in this case it is easier to check
if ((nowyear - birthyear > 18)
|| ((nowyear - birthyear == 18)&&(nowmonth - birthmonth > 0))
|| ((nowyear - birthyear == 18)&&(nowmonth == birthmonth)&&(nowday - birthday >= 0)))
// you're 18!
Upvotes: 1
Reputation: 54742
You have to mind leap-years, timezones... before reinventing the wheel, I recommend that you use DateJS.
if((18).years().ago().isBefore(birthdate)) {
// handle underage visitors
}
Upvotes: 2
Reputation: 67802
If you're looking for age, why not just go the simple route and deal with years, months, and days?
function findAge( birthday ){
var today = new Date();
var age = today.getFullYears() - birthday.getFullYears();
if( today.getMonth() - birthday.getMonth() < 0 ){
age--;
}
else if( today.getDay() - birthday.getDay() < 0 && today.getMonth() == birthday.getMonth() ){
age--;
}
}
Upvotes: 1