如何计算使用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();
}
我如何度的计算从出生日期起的年龄?
答
<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);
}
}
}
尝试使用的valueOf:VAR差= today.valueOf() - birthdate.valueOf(); – darron614