Retrieving Age from HTML5 Date Input in Angular 2+

I need assistance in calculating the age from a date input in an existing form using HTML5 and Angular. I want to achieve this without requiring the user to click anything.

Although I am able to retrieve the date, the format is causing issues with my code. Is there a way to modify the format or explore a more efficient alternative solution?

Any guidance or support on this matter would be greatly appreciated.

HTML:

<input type="date" name="dob" [(ngModel)]="birthdate">
<button (click)="getAge()">Get Age</button>
<input type="text" name="age" [(ngModel)]="data.age">

TS:

data: any;
birthdate: any;

constructor() {
 this.data = {};
 this.data.age = '';
 this.birthdate = this.birthdate;
}

public getAge() {
 console.log(this.birthdate);
 const timeDiff = Math.abs(Date.now() - this.birthdate);
 console.log(timeDiff);
 this.data.age = Math.floor((timeDiff / (1000 * 3600 * 24)) / 365);
 console.log(this.data.age);
}

Answer №1

//birthday variable represents the date of birth
function calculateAge(birthday)
{
    alert( new Date().getFullYear() - new Date(birthday).getFullYear());
}

calculateAge('11/07/1993');//calling the function

Answer №2

Kindly remember that this represents the exact age, which may appear as something like 26.5131, so you can choose how to convert it...

determineExactAge(birthDate:Date): number {
    const now = new Date();
    const age = (now - birthDate) / (31556952000); // 31556952000 equals 1 year in milliseconds
    return age;
}

Answer №3

When I needed to format the HTML5 type="date" input correctly, I turned to a solution that worked for me - https://github.com/JohannesHoppe/angular-date-value-accessor

In further research on ensuring accuracy in calculating age, I discovered that adding '.25' to the equation improved precision: Math.floor((timeDiff / (1000 * 3600 * 24)) / 365);

I hope this information proves helpful to others seeking to achieve similar results with Angular 2+

HTML:

<input type="date" name="dob" [(ngModel)]="birthdate" useValueAsDate>
<button (click)="getAge()">Get Age</button>
<input type="text" name="age" [(ngModel)]="data.age">

TS:

  data: any;
  birthdate: any;

  constructor() {
   this.data = {};
   this.data.age = '';
  }

  public getAge() {
   const timeDiff = Math.abs(Date.now() - this.birthdate);
   this.data.age = Math.floor((timeDiff / (1000 * 3600 * 24)) / 365.25);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Typescript to pass an optional parameter in a function

In my request function, I have the ability to accept a parameter for filtering, which is optional. An example of passing something to my function would be: myFunc({id: 123}) Within the function itself, I've implemented this constructor: const myFunc ...

Angular 4: Utilizing a class with a constructor to create an http Observable model

Within my application, I have a Class model that is defined with a constructor. Here is an example: export class Movie { title: string; posterURL: string; description: string; public constructor(cfg: Partial<Movie>) { Object ...

Cluster multiple data types separately using the Google Maps JavaScript API v3

I am looking to implement MarkerClusterer with multiple markers of various types and cluster them separately based on their type. Specifically, I want to cluster markers of type X only with other markers of type X, and markers of type Y with other markers ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

Obtain information from a CSV document within Highchart Angular

Is there a way to access and retrieve data from a CSV file stored in the assets folder of my local system? The CSV file contains 5 or 6 columns of information. Important: This is an Angular project, therefore jQuery is not available. ...

The constant issue persists as the test continues to fail despite the component being unmounted from the

import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { act } from 'react' import Notifications, { defaultNotificationTime, defaultOpacity, queuedNotificationTime, fa ...

The cdkDropListSortingDisabled attribute is not recognized as a valid property for the cdkDropList directive in Angular Material

I'm trying to achieve a specific use case where I need to drag and drop data from one zone (div) to another. After some research, I discovered that angular/material2 with the cdkDropList API could help me accomplish this task. Using the copyArrayitem ...

Issue with Angular routing not functioning properly post form submission

Recently, I created a contact form using Angular for the frontend and NodeJs with Nodemailer for the backend. However, I encountered an issue where after submitting the form, instead of redirecting to the default page set in the app, the page remains on th ...

Encountered an error saying "Unable to locate property '0' of undefined" while trying to access an environment variable in MongoDB

I am attempting to access a variable that is defined in my JavaScript code. This variable holds data fetched from a MongoDB using a GET request. The entire database is stored under this variable and then read by the HTML for display. The output of the GET ...

Is there a way to specifically target the MUI paper component within the select style without relying on the SX props?

I have been experimenting with styling the Select MUI component using the styled function. I am looking to create a reusable style and move away from using sx. Despite trying various methods, I am struggling to identify the correct class in order to direct ...

Version 2.0.0 of Angular working with Karma to offer Router capabilities

When a test requires an instance of the `Router`, simply providing the `Router` itself is not sufficient: import {Router} from '@angular/router'; import {it, inject, beforeEachProviders} from '@angular/core/testing'; import {Compo ...

Develop an Angular application with a customized URL path that utilizes a ServiceWorker

I am currently working on an Angular 10 application. It utilizes the Angular "service worker" to transform into a PWA. Once the app is compiled, it resides in "c:\-website-folder-\ng-app\dist". Users can access the app through a URL like: ...

Displaying messages in an Angular 2 chatbox from the bottom to the top

As a newcomer to using typescript, I am currently working on an angular 2 project and facing some challenges with creating a chatbox. My goal is to have new messages displayed at the bottom while pushing the old ones up one line at a time, as shown in this ...

Angular routing does not properly update to the child's path

I've organized my project's file structure as follows: app/ (contains all automatically built files) app-routing.module.ts components/ layout/ top/ side/ banner/ pages/ ...

Vercel is encountering difficulty locating a module or type declaration during the construction of a Next.js application

Currently, I'm facing an issue while trying to deploy a Next.js app to Vercel. The package react-swipeable appears to have its own type declarations but the build fails with the following error: Running "npm run build" ... > next build ... Failed t ...

Having trouble installing sub npm dependencies for a private npm module

I've created an npm private repository using Sinopia and published an app that is a complete end-to-end application built with Angular2 on the UI side. The package.json file contains dependencies such as @angular/core and animations. However, when I ...

Unable to retrieve any response data in Angular 2

I'm having trouble retrieving the response from my API. Despite being able to do so with PostMan, my variable "this.data" remains null. I've experimented with various approaches to no avail. Any assistance would be greatly appreciated. The method ...

The error message displayed by Create React App states: "You cannot utilize JSX without the '--jsx' flag."

I need help with overcoming this particular issue in a TypeScript based React application: Encountering an error stating "Cannot use JSX unless the '--jsx' flag is provided" ...

Update the Azure AD token with a personalized JWT token

We have developed an Angular 11 frontend application with a .NET 5 backend API. Our system offers two login options: 1. Basic authentication using user details stored in our system with JWT token generation, and 2. Azure AD authentication. During the Azu ...

Trouble arises in TypeScript when defining a class - SyntaxError crops up

When I try to declare a class, I encounter an error: // The code below is from my test1.ts file class WDesign { wModel: string; wQuer: string; } let logWDesign = (wd : WDesign) => { console.log(wd.wModel + " " + wd.wQuer); } let wd1 : WDe ...