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?
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.
<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);
}
}
}
It could be done using momentjs:
import * as moment from 'moment';
public calculateAge(birthdate: any): number {
return moment().diff(birthdate, 'years');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With