Calculate age from date in Angular 6 + Angular Material

Viewed 10683

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!

2 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);
    }
  }

This works to me:

  calculateAge(dateString) { // a date on string "22/10/1988
    let age: number;
    var dateParts = dateString.split("/");
    var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
    console.log(dateObject);
    
    if (dateString) {
      var timeDiff = Math.abs(Date.now() - new Date(dateObject).getTime());
      age = Math.floor(timeDiff / (1000 * 3600 * 24) / 365.25);
      console.log(age);
    }
    return age;
  }
Related