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

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

问题描述:

我有2个文本框。一个文本框将接受来自用户的出生日期,并基于出生日期,我想计算并在另一个文本框中显示他们的年龄。如何计算使用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> 

student.component.ts

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

} 

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

+0

尝试使用的valueOf:VAR差= today.valueOf() - birthdate.valueOf(); – darron614

<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> 

而在你的组件

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

} 
+1

它不工作。点击计算按钮后,我得到控制台上的错误“birthdate.getTime不是一个函数”。请建议替代 – Maximum

+0

@最大我已经更新它,现在就试试吧! –

+3

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