gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:06:29 25 4
gpt4 key购买 nike

我正在尝试从日期计算年龄,使用 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>

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

但我收到如下错误:
ERROR TypeError: this.birthdate.getTime is not a function

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

最佳答案

用下面的代码替换你的 typescript 代码。问题是 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);
}
}

关于angular - 从 Angular 6 + Angular Material 中的日期计算年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53113141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com