Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate age from birth date in Angular 2 using TypeScript

I have 2 textboxes. One textbox will accept birth date from the user and based on birth date I want to calculate and display their age in another textbox.

Here's my component class

Student.component.html

<div class="row">
<div class="input-field col m2">
    <input type="date" id="txtdate">
</div>
<div class="input-field col m4">
    <input type="number" id="age">
</div>

student.component.ts

 import { Component, OnInit } from '@angular/core';

@Component( {
 selector: 'stud',
 templateUrl: './student.component.html'
 })
 export class StudentComponent implements OnInit
{

     constructor() { }

     ngOnInit() { }

}
function CalculateAge()
{
     var birthdate = <HTMLElement>document.getElementById( "txtdate" );
     var dt = new Date();
     var today = dt.getDate();

}

How do I calculate age from birth date?

like image 368
AshwaniKumar Singh Avatar asked Jan 22 '17 14:01

AshwaniKumar Singh


3 Answers

There is slight mistake in above code at two places and the fixes are below. We need to use .getTime() function to get milliseconds of birthday and 365.25 to round up 29 Feb thing as in the following:

let timeDiff = Math.abs(Date.now() - this.birthdate.getTime());
let age = Math.floor((timeDiff / (1000 * 3600 * 24))/365.25);
console.log(age)

After these two changes it will give you correct age right up till 364th day of the year.

like image 110
Zahid Mir Avatar answered Sep 20 '22 04:09

Zahid Mir


<div class="row">
    <div class="input-field col m2">
        <input type="date" [(ngModel)]="birthdate" id="txtdate">
    </div>
    <div class="input-field col m4">
        <input type="number" [(ngModel)]="age" id="age">
    </div>
    <button (click)="CalculateAge()">Calculate Age</button>
</div>

And in your component

 import { Component, OnInit } from '@angular/core';
@Component( {
 selector: 'stud',
 templateUrl: './student.component.html'
 })
 export class StudentComponent implements OnInit
{
    public birthdate: Date;
    public age: number;

     constructor() { }

     ngOnInit() { }

     public CalculateAge(): void
     {
         if(this.birthdate){
            var timeDiff = Math.abs(Date.now() - this.birthdate);
            //Used Math.floor instead of Math.ceil
            //so 26 years and 140 days would be considered as 26, not 27.
            this.age = Math.floor((timeDiff / (1000 * 3600 * 24))/365);
        }
    }

}
like image 40
Ali Baig Avatar answered Sep 22 '22 04:09

Ali Baig


It could be done using momentjs:

import * as moment from 'moment';

public calculateAge(birthdate: any): number {
  return moment().diff(birthdate, 'years');
}
like image 38
Strider Avatar answered Sep 20 '22 04:09

Strider