11

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.

Here's my component class

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

}

How do I calculate age from birth date?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
AshwaniKumar Singh
  • 241
  • 1
  • 3
  • 12
  • try using valueOf: var difference = today.valueOf() - birthdate.valueOf(); – darron614 Jan 22 '17 at 14:34
  • 1
    Possible duplicate of [Calculate age given the birth date in the format YYYYMMDD](https://stackoverflow.com/questions/4060004/calculate-age-given-the-birth-date-in-the-format-yyyymmdd) – Heretic Monkey Nov 02 '18 at 14:25
  • Most answers to this question are incorrect. All answers not using momentjs are incorrect, each has a bug. Proper way in 2022 is using dayjs (30x less bundle size than moment), or use a duplicate link above. Let's close this question, to prevent more incorrect answer spam. – Victor Zakharov May 05 '22 at 12:46

6 Answers6

21

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:

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.

WasiF
  • 26,101
  • 16
  • 120
  • 128
Zahid Mir
  • 226
  • 2
  • 3
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>

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

}
Ali Baig
  • 3,819
  • 4
  • 34
  • 47
  • 1
    Its not working. After clicking on calculate button i am getting error on console "birthdate.getTime is not a function ". Please suggest alternative – AshwaniKumar Singh Jan 26 '17 at 15:47
  • 6
    I am still facing some issues at this line "var timeDiff = Math.abs( Date.now() - this.birthdate );" its showing me error at this.birthdate error : "The right hand side of arithmetic operator must be of type any or number" – AshwaniKumar Singh Jan 27 '17 at 04:00
  • I don't see any issues with this part of the code, see `https://plnkr.co/edit/nwUtcjthyshpjOmxmPdz` here for age calculation. Make sure you have defined the birthday above as I have shown above – Ali Baig Jan 28 '17 at 01:05
  • 1
    The exact same code from above gives me continuously this error: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." pointing to this.birthdate Angular 4.2.4 - is this a bug in angular? Did they change anything important there? – user3387542 Nov 29 '17 at 10:22
  • 1
    This finally helped: https://stackoverflow.com/questions/42622299/date-difference-in-hours-angular-2 let diffInMs: number = Date.parse(date2) - Date.parse(date1); – user3387542 Nov 29 '17 at 10:28
  • I would change two things: 1. 365 to 365.25, since today is the Feb. 28th 2018 and Mar. 6th returns 26 even though its incorrect 2. to avoid "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." error: this.birthdate.getTime() – matt4692 Feb 28 '18 at 10:05
5

It could be done using momentjs:

import * as moment from 'moment';

public calculateAge(birthdate: any): number {
  return moment().diff(birthdate, 'years');
}
Strider
  • 3,539
  • 5
  • 32
  • 60
2

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

}
1

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);
}
Mahadev
  • 51
  • 5
0

This will also work.

calculateAge(dob) {
    if (!dob || dob == "") return "";
    let mdob = moment(dob, "YYYY-MM-DD");
    let age = moment().diff(mdob, "months");
    let yrs = (age / 12).toFixed(1);
    let mnths = age % 12;
    return `${parseInt(yrs)}Y`;
}
Tim
  • 5,435
  • 7
  • 42
  • 62
Jhansi ravula
  • 51
  • 1
  • 10