【发布时间】:2022-01-14 09:05:24
【问题描述】:
所以,我设法让它工作,但 2004 年返回到 18 岁以下。 假设我将年份设置为 2004 年 1 月 13 日,它返回年龄为 18 岁,但也返回他们未满 18 岁。这也适用于 1 月份中满足 18 岁要求的任何一天。这是函数检查年龄和日期。在这一点上我最好的猜测可能是时区问题?
GetAge(date: string): number {
let today = new Date();
let birthDate = new Date(date);
let age = today.getFullYear() - birthDate.getFullYear();
let month = today.getMonth() - birthDate.getMonth();
if (month < 0 || (month === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
console.log('Age: ' + age + '\nBirthday: ' + birthDate);
return age;
}
AgeCheck(controlName: string): ValidatorFn {
return (controls: AbstractControl) => {
const control = controls.get(controlName);
if (control?.errors && !control.errors['under18']) {
return null;
}
if (this.GetAge(control?.value) <= 18) {
return { under18: true }
} else {
return null;
}
}
}
我用这个作为日期选择输入
<ion-input type="date" formControlName="dateofbirth"></ion-input>
这是 FormBuilder 的一个示例
this.credentials = this.fb.group({
dateofbirth: ['', [Validators.required]],
}, {validator: [this.AgeCheck('dateofbirth')]});
【问题讨论】:
标签: node.js angular ionic-framework