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

时间:2017-01-22 14:22:24

标签: angular typescript

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

}

如何计算出生日期的年龄?

5 个答案:

答案 0 :(得分:5)

上面的代码在两个地方有一些小错误,下面是修复程序。 我们需要使用.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)

这两项更改之后,您将可以正确地调整年龄直到一年的第364天。

答案 1 :(得分:3)

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

}

答案 2 :(得分:1)

这可能有帮助。

if (this.dob) {
  //convert date again to type Date
  const bdate = new Date(this.dob);
  const timeDiff = Math.abs(Date.now() - bdate.getTime() );
  this.age = Math.floor((timeDiff / (1000 * 3600 * 24)) / 365);
}

答案 3 :(得分:1)

Age Calculate as year, month,days

if (dobDate!=undefined) { 
  var todayDate=new Date();
  var ageyear = todayDate.getFullYear() - dobDate.getFullYear();
  var agemonth = todayDate.getMonth() - dobDate.getMonth();
  var ageday = todayDate.getDate() - dobDate.getDate();

  if (agemonth <= 0) {
    ageyear--;
    agemonth = (12 + agemonth);
  }
  if (nowDay < dobDay) {
    agemonth--;
    ageday = 30 + ageday;
  }  if (agemonth == 12) {
    ageyear = ageyear + 1;
    agemonth = 0;
  }

  alert("Age in Year:" + ageyear + ',' + 'Month:' + agemonth + ',' + 'Day:' + ageday);

}

答案 4 :(得分:1)

可以使用momentjs

import * as moment from 'moment';

public calculateAge(birthdate: any): number {
  return moment().diff(birthdate, 'years');
}