We can use native date methods to calculate the age of a person given the birth date in YYYY-MM-DD format.
To do this, we write:
const calculateAge = (birthday) => {
const ageDifMs = Date.now() - new Date(birthday).getTime();
const ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
console.log(calculateAge('1960-01-21'))
We create the calculateAge
method with the birthday
parameter that takes a date string that we can convert to a date to calculate the age based on it.
In the function, we subtract Date.now
, which has the timestamp of the current date-time in milliseconds.
And we create a new Date
instance and call getTime
to get the timestamp of the birthday
we pass in milliseconds.
Then we assign the result to ageDifMs
.
Then we pass in ageDifMs
to the Date
constructor to get the ageDate
which is the date that’s created from January 1, 1970 midnight UTC plus the timespan specified by the timespan we pass in.
We call getUTCFullYear
to get the year minus 1970 to get the age.
Then call Math.abs
to make sure it’s positive regardless of whether birthday
is before January 1, 1970 midnight UTC or not.
Therefore, the console log should log 61.
Using moment.js
To make calculate the date difference easier, we can use the moment.js library.
To do this, we write:
const calculateAge = (birthday) => {
const startDate = new Date();
const endDate = new Date(birthday);
return Math.abs(moment.duration(endDate - startDate).years());
}
console.log(calculateAge('1960-01-21'))
In the calculateAge
function, we take the birthday
parameter like we have before.
But instead of using native date methods, we use the moment.duration
method to calculate the duration.
We call it with endDate — startDate
to get the moment duration object.
Then we call years
to get the duration as the number of years.
And then we call Math.abs
to make sure that the number returned is positive.
Then the console log should give us the same result as before.