I am trying to calculate age from the date, picked up with Angular Material date picker, but have an error. Below is my code:
HTML
<div class="input-container">
<mat-form-field>
<input matInput [matDatepicker]="dp" placeholder="Date of Birth" [(ngModel)]="birthdate" formControlName="firstCtrl">
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp></mat-datepicker>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Age" value="{{age}}" [(ngModel)]="age" formControlName="firstCtrl" required>
</mat-form-field>
<button mat-button (click)="CalculateAge()">Calculate Age</button>
</div>
TS
export class ClaimSubmitComponent implements OnInit {
public birthdate: Date;
public age: number;
public CalculateAge(): void {
if (this.birthdate) {
var timeDiff = Math.abs(Date.now() - this.birthdate.getTime());
this.age = Math.floor(timeDiff / (1000 * 3600 * 24) / 365.25);
}
}
But I get an error like:
ERROR TypeError: this.birthdate.getTime is not a function
What am I doing wrong? Thank you!
Replace your typescript code with below code. problem is this.birthDate is string during calculation time. I have created sample application please check on stackblitz
export class ClaimSubmitComponent implements OnInit {
public birthdate: Date;
public age: number;
public CalculateAge(): void {
if (this.birthdate) {
var timeDiff = Math.abs(Date.now() - new Date(this.birthdate).getTime());
this.age = Math.floor(timeDiff / (1000 * 3600 * 24) / 365.25);
}
}
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