Ionic 2 how to get age from DOB?

ionic 2 i want to get age from DOB and DOB is taken in yyyy-mm-dd (2018-02-23) format from date-time picker

Hi @demokumar,


  <ion-datetime displayFormat="MM/DD/YYYY" [(ngModel)]="myDate" (ionChange)="getDate($event)"></ion-datetime>


in class declare one variable as


After that create one function like

getDate(newdate) {

this will get you the selected date object from date time picker.

hi @addwebsolution
I get date from date time picker but I want to calculate age from Date Of Birth

try using split…
the below code subtracts two dates… the format for date picker is yyyy-mm-dd
0-1-2 the 2 in the braces means “dd” (1 means mm and 0 means yyyy)
so if var1 date is 25 and var2 date is 21 it wii do : 25-21 = 4.
var date1="-")[2];
var date2=this.from.split("-")[2];
var days= parseInt(date1)-parseInt(date2);

1 Like

thnx @uddyvky
difference between yyyy gives Age like this :
var date1 =…split("-")[0];
var date2 = this.from…split("-")[0];
this.age= parseInt(date1) - parseInt(date2);

yes 0 here refers to year i.e yyyy.

Just an FYI, @AaronSterling published an npm package that might handle this situation really well. It has a “distance between dates” function.

1 Like

This is a typescript / javascript question than ionic.
Check these links out:

Their javascript examples will inspire you.

1 Like

An overview of what should happen in typescript:

year, month, day should be declared as variables which can be passed through input.
When users select DOB, calculate their age by subtracting variables from current date (2/23/2018).
You can then return the final value to where you want to display users’ age.

1 Like

Thnx @jamesharvey for this information it gives actual and exact age.

1 Like