0

How to calculate age of users when they are entered their date of birth in react-native?

I want to check user is more then 18 year or not.When they are entered date of birth .

I am using react-native-datepicker for take user's date of birth.

I am trying to calculate age of user using below code but it not work properly .So please help me .How i can achieve this functionality.

calculate_age = (date) => {
        var today = new Date();
        var birthDate = new Date(date); 
        console.log("get bod-->",birthDate) // create a date object directly from `dob1` argument
        var age_now = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age_now--;
        }
        console.log('my age', age_now);
        return age_now;
    }

    onDateChange = (date) => {
        this.setState({ date: date }, () => {
            console.log(date)
            if (this.calculate_age(date) < 18) {
                alert("You Are Not Eligable")
            } else {

            }
        })
    }
Raghusingh
  • 398
  • 3
  • 10
  • 33
  • 2
    https://stackoverflow.com/questions/25150570/get-hours-difference-between-two-dates-in-moment-js you can use moment.js package if working with dates – Geetanshu Gulati Feb 26 '20 at 07:40
  • I just tried your calculate_age() and it worked from me. I think the issue is at passing the parameter to the function call. this.calculate_age(new Date(1994, 3, 24)) <- Once try with this. – HungrySoul Feb 26 '20 at 07:50

2 Answers2

0

You can make a custom function like this:

const  getAge = (dateString)=>{
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
console.log('age: ' + getAge("1980/08/10"));
Dharman
  • 30,962
  • 25
  • 85
  • 135
Gaurav Roy
  • 11,175
  • 3
  • 24
  • 45
0

Using 'npm i moment' package.I solved this problem.

onDateChange = (date) => {
    this.setState({ date: date }, () => {
        if (this.calculate_age(Moment(date,"DD-MM-YYYY").format("YYYY-MM-DD")) <= 17 ) {

            this.setState({errmsg:"You must be atleast 18 years of old to join."})
        }else{
            this.setState({errmsg:" "})
        }
    })
}
Raghusingh
  • 398
  • 3
  • 10
  • 33