Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate age from date in Angular 6 + Angular Material

Tags:

angular

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!

like image 875
Andrew Avatar asked Jan 27 '23 05:01

Andrew


1 Answers

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);
    }
  }
like image 156
Ajay Ojha Avatar answered Jan 30 '23 11:01

Ajay Ojha