Mike Rifgin
Mike Rifgin

Reputation: 10745

Problem with comparing dates in javascript

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

Answers (4)

Martin Hennings
Martin Hennings

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

Faber
Faber

Reputation: 2194

try to take a look at this post

Upvotes: -1

Marcel Jackwerth
Marcel Jackwerth

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

Stefan Kendall
Stefan Kendall

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

Related Questions