如何使用TypeScript从Angular 2中的出生日期算起年龄

Max*_*mum 5 typescript angular

我有2个文本框。一个文本框将接受用户的出生日期,并根据我想计算的出生日期并在另一个文本框中显示其年龄。

这是我的组件类

Student.component.html

<div class="row">
<div class="input-field col m2">
    <input type="date" id="txtdate">
</div>
<div class="input-field col m4">
    <input type="number" id="age">
</div>
Run Code Online (Sandbox Code Playgroud)

学生组件

 import { Component, OnInit } from '@angular/core';

@Component( {
 selector: 'stud',
 templateUrl: './student.component.html'
 })
 export class StudentComponent implements OnInit
{

     constructor() { }

     ngOnInit() { }

}
function CalculateAge()
{
     var birthdate = <HTMLElement>document.getElementById( "txtdate" );
     var dt = new Date();
     var today = dt.getDate();

}
Run Code Online (Sandbox Code Playgroud)

我如何从出生日期算起年龄?

小智 7

上面的代码在两个地方有轻微的错误,下面是修复程序。我们需要使用 .getTime()函数来获取生日的毫秒数和365.25来舍入2月29日的内容,如下所示:

let timeDiff = Math.abs(Date.now() - this.birthdate.getTime());
let age = Math.floor((timeDiff / (1000 * 3600 * 24))/365.25);
console.log(age)
Run Code Online (Sandbox Code Playgroud)

经过这两次更改后,它会为您提供正确的年龄,直到直到第364天。


Str*_*der 6

可以使用momentjs来完成:

import * as moment from 'moment';

public calculateAge(birthdate: any): number {
  return moment().diff(birthdate, 'years');
}
Run Code Online (Sandbox Code Playgroud)


Ali*_*aig 5

<div class="row">
    <div class="input-field col m2">
        <input type="date" [(ngModel)]="birthdate" id="txtdate">
    </div>
    <div class="input-field col m4">
        <input type="number" [(ngModel)]="age" id="age">
    </div>
    <button (click)="CalculateAge()">Calculate Age</button>
</div>
Run Code Online (Sandbox Code Playgroud)

在你的组件中

 import { Component, OnInit } from '@angular/core';
@Component( {
 selector: 'stud',
 templateUrl: './student.component.html'
 })
 export class StudentComponent implements OnInit
{
    public birthdate: Date;
    public age: number;

     constructor() { }

     ngOnInit() { }

     public CalculateAge(): void
     {
         if(this.birthdate){
            var timeDiff = Math.abs(Date.now() - this.birthdate);
            //Used Math.floor instead of Math.ceil
            //so 26 years and 140 days would be considered as 26, not 27.
            this.age = Math.floor((timeDiff / (1000 * 3600 * 24))/365);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 我在这一行仍然面临一些问题“var timeDiff = Math.abs( Date.now() - this.birthdate );” 它向我显示了 this.birthdate 错误:“算术运算符的右侧必须是任何类型或数字” (6认同)