Calculate age using ionic date-time picker

Hi, can anyone help me with working code .How to calculate age based on the date input given by user . Using ionic 2.tried lot did not get any working code.

have you tried to make today as a variable and assign it as a date of today then subtract your date type variable for date born?

/**

  • Returns age from date of birth
  • @param {Date} date
  • @returns {Number}
    */
    function getAge(date) {
    var now = new Date();
    var age = now.getFullYear() - date.getFullYear();
    return age;
    };

// iso date time
var dateOfBirth = new Date(‘1982-03-28 00:00:00’);

// calculate age
var age = getAge(dateOfBirth);

// output
console.log(age);

I greatly prefer moment over JavaScript’s stock Date object.

1 Like

Thanks for the reply .Hey I tried this code since ionic 2 uses typescript.it shows error for get full year is not found . this is what i tried:

html;

  <ion-item>
  <ion-label stacked>Enter Date of Birth</ion-label>
    <ion-datetime type="date" 
        name="dob" [(ngModel)]="birthdate"  displayFormat="DD-MM-YYYY"  >
  </ion-datetime>
</ion-item>



  <ion-item>
  <ion-label stacked>Age:</ion-label>
   <ion-input type="text" name="age"  [(ngModel)]="data.age" > </ion-input> 

</ion-item>

ts:

data:any;
birthdate:any;

constructor(public navCtrl: NavController) {

    this.data = {};
    this.data.age = '';
    this.birthdate=this.birthdate;

}

public getAge()

{

console.log(this.birthdate);
    

    var timeDiff = Math.abs(Date.now() - this.birthdate);
       
         console.log(timeDiff);


        this.data.age = Math.floor((timeDiff / (1000 * 3600 * 24))/365);


    console.log(this.data.age);

}

Thanks

Don’t bind <ion-datetime> to JavaScript Date objects. Bind them to ISO 9601 strings.

1 Like

i did not get it. can you help me with code

The docs can.

i followed that link , it shows the using the ion-date time picker i want know how to pass the picked date into component i.e to ts file and calculate the age onchnage of the