从 Angular 6 + Angular Material 中的日期计算年龄

And*_*rew 3 angular

我正在尝试从日期计算年龄,使用 Angular Material 日期选择器获取,但出现错误。下面是我的代码:

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>
Run Code Online (Sandbox Code Playgroud)

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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

但我收到如下错误:

ERROR TypeError: this.birthdate.getTime is not a function
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?谢谢!

小智 7

用下面的代码替换你的打字稿代码。问题是 this.birthDate 在计算时间是字符串。我已经创建了示例应用程序,请查看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);
    }
  }
Run Code Online (Sandbox Code Playgroud)