Solution

To calculate age from date of birth in React, you can use moment library diff() method.

You have to use just like it currentDate.diff(dobDate, 'years') and it will return differance year between currentDate and dobDate.

Snippet

In this snippet, we will create take current date and date of birth date.

Apply moment library diff() method with years parameter to get differance year.

// Get the current date
let currentDate = moment(new Date());

// Get date of birth date
let dobDate = moment(new Date('1999-12-31'));

// get no of year
let year = currentDate.diff(dob, 'years');

console.log(year);

Example

In this example, we will show age when use select their date of birth in input field.

Let’s Do following task to calculate age from date of birth.

  • Install moment library
npm install moment --save
  • Create Date input field where user can select their date of birth.
  • On the selection of date call calculateAge() function which can do calculation and store age in the state.
  • At the end show the age in the React UI.
import React, { useState } from "react";
import moment from "moment";

export default function App() {
  const [dob, setDob] = useState(new Date());
  const [age, setAge] = useState(0);

  const calculateAge = (dateOfBirth) => {
    setDob(dateOfBirth);
    const currentDate = moment();
    const dob = moment(dateOfBirth);
    setAge(currentDate.diff(dob, "years"));
  };

  return (
    <div className="App">
      <input
        type="date"
        onChange={(e) => calculateAge(e.target.value)}
        value={dob}
      />
      <h1>{`Age`}</h1>
      <p>{age}</p>
    </div>
  );
}

Output

calculateAge, date

codesandbox