Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To check if age is not less than 13 years in javascript

Tags:

javascript

Can anyone please guide me through javascript function, which will fetch me year difference between current date and date entered by user

I have tried this, but it doesnot keep in count leap years

var yearOld=2000
var dateOld=11
var mnthOld=1;
var currendDate=new Date(); // 9 - jan - 2013

var oldDate=new Date(yearOld,mnthOld-1,dateOld);

var timeDiff =currendDate-oldDate ;

var diffDays = timeDiff / (1000 * 3600 * 24 * 365); 

Result is coming 13.00789 something where it should come less than 13

Any help will be appreciated

like image 369
ap.singh Avatar asked Jan 09 '13 08:01

ap.singh


2 Answers

function getAge(birthDateString) {
    var today = new Date();
    var birthDate = new Date(birthDateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

if(getAge("27/06/1989") >= 18) {
    alert("You have 18 or more years old!");
} 
like image 166
Dawid Sajdak Avatar answered Sep 28 '22 17:09

Dawid Sajdak


If you have good amount of Date related operations, consider using MomentJS http://momentjs.com/ . Check the first two examples there and i guess they fit your question.

like image 21
Mahbub Avatar answered Sep 28 '22 15:09

Mahbub