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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41792026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:11:28  来源:igfitidea点击:

How do I calculate age from birth date in Angular 2 using TypeScript

angulartypescript

提问by Maximum

I have 2 textboxes. One textbox will accept birth date from the user and based on birth date I want to calculate and display their age in another textbox.

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

Here's my component class

这是我的组件类

Student.component.html

学生组件.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

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

}

How do I calculate age from birth date?

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

回答by Zahid Mir

There is slight mistake in above code at two places and the fixes are below. We need to use .getTime()function to get milliseconds of birthday and 365.25 to round up 29 Feb thing as in the following:

以上代码有两处小错误,修复如下。我们需要使用 .getTime()函数来获取生日的毫秒数和 365.25 来四舍五入 29 Feb 的事情,如下所示:

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

After these two changes it will give you correct age right up till 364th day of the year.

在这两个更改之后,它将为您提供正确的年龄,直到一年中的第 364 天。

回答by Ali Baig

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

And in your component

在你的组件中

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

}

回答by Nazmul Nadim

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

}

回答by Strider

It could be done using momentjs:

可以使用momentjs来完成:

import * as moment from 'moment';

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

回答by Mahadev

This might help.

这可能会有所帮助。

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