Search code examples
javascriptangular

Calculate Years, Months, Days from Date of Birthday using Angular 17


I'm able to calculate the Age but not Month and Days correctly.

Here's the HTML Code with Angular 17 binded:

<div class="row">
  <div class="col">
    <label for="dob" class="form-label">Date of Birth</label>
    <input type="date" class="form-control" [(ngModel)]="item.dob" placeholder="DD/MM/YYYY">
  </div>
  <div class="col">
    <button type="button" (click)="ageCalculator()">Calculate</button>
    <p *ngIf="item.dob">Age {{item.ageYears}}</p>
    <p *ngIf="item.dob">Month {{item.ageMonths}}</p>
    <p *ngIf="item.dob">Days {{item.ageDays}}</p>
  </div>
</div>

Here's the .TS file but as mentioned above, I don't understand the formula used:

ageCalculator(){
    if(this.item.dob){
      const convertAge = new Date(this.item.dob);
      const timeDiff = Math.abs(Date.now() - convertAge.getTime());
      this.item.ageYears = Math.floor((timeDiff / (1000 * 3600 * 24))/365);
      this.item.ageMonths = Math.floor((timeDiff % (31536000000))/2628000000);
      this.item.ageDays = Math.floor((timeDiff % 31536000000))/86400000;
    }
  }

Where am I going wrong?

Please note that the numbers used in calculation were picked from other questions/answers. I don't fully understand it.


Solution

  • First, you need to get the subtraction between the year, month, day of now and the birthday, and if the days value is negative the month rolled over before reaching the birthday of the current month. Adjust the months and calculate the days using the days of the previous month., the same applies to months if negative we need to adjust the years and months

      ageCalculator() {
        if (this.item.dob) {
          const birthDate = new Date(this.item.dob);
          const currentDate = new Date();
          
          let years = currentDate.getFullYear() - birthDate.getFullYear();
          let months = currentDate.getMonth() - birthDate.getMonth();
          let days = currentDate.getDate() - birthDate.getDate();
    
          if (days < 0) {
            months--;
            let previousMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0);
            days = previousMonth.getDate() + days;
          }
    
          if (months < 0) {
            years--;
            months = 12 + months;
          }
    
          this.item.ageYears = years;
          this.item.ageMonths = months;
          this.item.ageDays = days;
        }
      }
    

    But,I suggest you use a date library to do that like date-fns, it makes much easier to do these operations.