Have you ever visited a site that told you your exact age in days, months and years?, most likely not (lol), so I will introduce you to one today thanks to this project from Front End Mentor. I'll be explaining the underlying logic behind calculating a person's age in days, months and years using React and a date library that makes it easy to work with dates.
Here's a live preview of the project: Link.
I assume you already have knowledge of React (basic understanding is fine), so I will skip over installation and setting up a React project.
The Core Idea
Calculating a person's age means finding the difference between two dates: The person's birth date and today’s date, but because months have different lengths (and leap years exist), it’s not as simple as subtracting years directly. If you have ever worked with dates before, you know how stressful they can be.
I personally hate working with dates 😅, as they get complicated and confusing quickly. Due to the difficulty involved in using dates, solutions have been built to make working with them easier; one such solution is the dayjs library. I particularly love this library because of the helpful methods it provides for retrieving date information. It also allows you to combine methods together to form your own date validation logic. We would use this library to perform the age calculation.
Building The Age Calculation Logic
Let's create a React component for the UI of the form
import { useState } from "react";
function App() {
const [formValues, setFormValues] = useState({
day: "",
month: "",
year: "",
});
const [output, setOutput] = useState({
day: "",
month: "",
year: "",
});
function handleFormValues(e) {
setFormValues((prevState) => {
return {
...prevState,
[e.target.name]: e.target.value,
};
});
}
return (
<>
<main className="age-container">
<form>
<div className="form-container">
<div className="input-group">
<label htmlFor="day">Day</label>
<input
type="text"
id="day"
name="day"
value={formValues.day}
onChange={handleFormValues}
placeholder="DD"
/>
</div>
<div className="input-group">
<label htmlFor="month">Month</label>
<input
type="text"
id="month"
name="month"
value={formValues.month}
onChange={handleFormValues}
placeholder="MM"
/>
</div>
<div className="input-group">
<label htmlFor="year">Year</label>
<input
type="text"
id="year"
name="year"
value={formValues.year}
onChange={handleFormValues}
placeholder="YYYY"
/>
</div>
</div>
<button type="submit" className="submit-btn">
Calculate
</button>
</form>
<div id="result">
<h2>
<span>{output.year}</span> years
</h2>
<h2>
<span>{output.month}</span> months
</h2>
<h2>
<span>{output.day}</span> days
</h2>
</div>
</main>
</>
);
}
export default App;
I will skip styling the form, and validating the inputs, they are not important for this article.
Inside our component, let's handle the logic to calculate the users age when they submit the form.
import { useState } from "react";
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
dayjs.extend(customParseFormat);
function App() {
const [formValues, setFormValues] = useState({ ... });
const [output, setOutput] = useState({ ... });
function handleFormValues(e) { ... }
function handleSubmit(e) {
e.preventDefault();
const { day, month, year } = formValues;
let noOfMonths = 0;
let noOfDays = 0;
const currentDate = dayjs();
const inputDate = dayjs(`${year}-${month}-${day}`);
const checkValidDate = dayjs(
`${year}-${month}-${day}`,
"YYYY-MM-DD",
true,
).isValid();
if (!checkValidDate) {
return new Error("Date is Invalid")
}
if (inputDate.month() > currentDate.month()) {
noOfMonths = 12 - (inputDate.month() - currentDate.month());
} else {
noOfMonths = currentDate.month() - inputDate.month();
}
if (inputDate.date() > currentDate.date()) {
noOfDays =
inputDate.daysInMonth() - (inputDate.date() + currentDate.date());
} else {
noOfDays = inputDate.date() - currentDate.date();
}
const yearDiff = Math.abs(inputDate.diff(currentDate, "year"));
const monthDiff = Math.abs(noOfMonths);
const dayDiff = Math.abs(noOfDays);
setOutput((prevState) => {
const newOutput = {
...prevState,
day: dayDiff,
month: monthDiff,
year: yearDiff,
};
return newOutput;
});
}
return (
<>
<main className="age-container">
<form onSubmit={handleSubmit}>...</form>
<div id="result">
<h2>
<span>{output.year}</span> years
</h2>
<h2>
<span>{output.month}</span> months
</h2>
<h2>
<span>{output.day}</span> days
</h2>
</div>
</main>
</>
);
}
export default App;
What’s Happening Here?
We first import the dayjs library and a plugin to extend the functionality of dayjs.
Why is this plugin necessary?
By default, day.js can only parse standard date formats (like ISO strings), but it cannot parse custom date formats e.g "February 20th, 2026", this is where the customParseFormat plugin comes in. With this plugin, we can extend the functionality of dayjs to parse custom dates. Even though we imported this plugin, this particular line is important
dayjs.extend(customParseFormat);
This line tells dayjs to enable this plugin and add its features to the core library. Without it, the plugin has no effect and we won't be able to parse any custom date.
- Secondly, we assign the current date gotten from calling
dayjs()into a variable to have one instance of that function call we can use multiple times. - We pass the day, month and year values gotten from our form into
dayjs()to convert the date into a day.js date object we can work with. - We then check if the date passed in by the user is valid, if it isn't, we return an error and stop the remaining code from executing.
The main logic starts when we want to calculate how old a user is in months and days.
How no of months is calculated
If the user's birth month is greater than the current month, that means they have not yet reached their birth month, so we can't just minus the current month from the user's birth month alone. To get the right month value, we first minus the current month from the user's birth month, then substract the result from 12 (12 being the total number of months in a year).
If the user's birth month is less than or equal to the current month, this means they have already passed their birth month or the current month is their birth month, so we can just substract the current month from their birth month directly.
Once we've gotten the right month value, we store it in the noOfMonths variable.
How no of days is calculated
Moving over to calculating the users age in days, if the day of the user's birthday is greater than the day of the current date, that also means they haven't reached their birthday yet, so we add the day of the user's birthday to the day of the current date and minus it from the number of days that month has, because months have different no of days in them e.g february (28), March (31) etc, so doing it like this ensures we are considering the correct amount of days a month has. If the day of the users birthday is not greater than the day of the current date, we just minus the day of the users birthday from the day of the current date. We store the result of this calculation inside the noOfDays variable.
Calculating the Year
Calculating the year is the simplest thing we have to do, we just minus the users birth year from the current year to get how old they are in years. I wish the rest where this straight forward!.
After running all these calculations, we use the abs() function to convert negative values to positive equivalents before outputting the result in the UI.
Now I know this might have been confusing for you, day of the users birthday, month of the current month 😂😂, what's this guy even saying?, it took me a while to understand it as well, so it's perfectly fine if you're not getting it. This is why I said working with dates is confusing and frustrating, but that's why libraries like dayjs makes this a bit simpler but you still have to do some calculations, but imagine doing this calculation using JavaScript's Date() object?, it will most likely be 10x harder.
Conclusion
This basically is the whole process involved in calculating a users age in days, months and years. Age calculation doesn't have to be a difficult task, with the right logic and a helping hand from libraries like day.js, you can turn a tedious math problem into a simple solution.
Thanks for sticking to the end (if you did). I am Oyinkansola, a front end developer helping service-based businesses attract their ideal customers online through well engineered websites. You can check out my Portfolio and follow me on X and LinkedIn.
Top comments (0)