简体   繁体   English

ion-datetime - 从出生日期计算年龄

[英]ion-datetime - calculate age from birthdate

I'm using ion-datetime picker to get the user's date of birth.我正在使用 ion-datetime 选择器来获取用户的出生日期。 I want to calculate the user's age based on their input.我想根据他们的输入计算用户的年龄。 Not sure why the below isn't working...不知道为什么下面的不起作用...

html html

<ion-datetime [(ngModel)]="userInfo.dateOfBirth"></ion-datetime>

typescript打字稿

public ageFromDOB(dateOfBirth) {
  const today = new Date();
  const birthdate = new Date(dateOfBirth);
  this.userInfo.age = today.getFullYear() - birthdate.getFullYear();
  const month = today.getMonth() - birthdate.getMonth();
  if ( month < 0 || (month === 0 && today.getDate() < birthdate.getDate())) {
    this.userInfo.age--;
  }
  return this.userInfo.age;
} 

The problem is probably the place where you're calling it from.问题可能出在您调用它的地方。

It's confusing with typescript projects as everything is async and it can run before something is populated and seem like its not working.它与打字稿项目令人困惑,因为一切都是异步的,它可以在填充某些内容之前运行,并且似乎无法正常工作。

The ion-datetime has an ionChange event: ion-datetime有一个ionChange事件:

ionChange ion-datetime - Ionic Documentation ionChange 离子日期时间 - Ionic 文档

You should update the age when the datetime is changed:您应该在更改日期时间时更新年龄:

<ion-datetime [(ngModel)]="userInfo.dateOfBirth" (ionChange)="ageFromDOB($event)"></ion-datetime>

You will still need to do a bit of homework I think:我认为您仍然需要做一些功课:

public ageFromDOB(dateOfBirth) {
  console.log(dateOfBirth);
}

And then see what format the date is supplied in... seems like it's maybe an object but I'm just looking at github issues , which seems to say:然后查看提供的日期格式......似乎它可能是一个对象,但我只是在看 github 问题,它似乎在说:

 updateMyDate($event) {
    const day: number = $event.detail.value.day.value;
    const month: number = $event.detail.value.month.value;
    const year: number = $event.detail.value.year.value;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM