Show age of my team members with a dataset

I’m currently making a dynamic page with all my team members. I would like to add the age of the team members to the website. In the dataset (which I use to create the page with team members) is a column with the dates of birth of all the team members. Is it possible to calculate the age with these dates of birth and display their age in a box with their photo’s and names.

$w.onReady(function() {
    console.log(getAge("1980/08/10"));
    // or...
    console.log(getAge("1982.05.23"));
});
function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

Take a look into console!

Hi there, thre’s a better way to achieve this, with a help of an npm package called moment .

import moment from 'moment';

function getAge(date) {
    const y = date.getFullYear();
    const m = date.getMonth() + 1;
    const d = date.getDate();
    
    return moment(`${y}-${m}-${d}`).fromNow();
}

You can read more about moment.js here.

Hope this helps~!
Ahmad

Yes nice one Ahmad. But install an extra npm-package for this little pupose?
Idk. :neutral_face:

@russian-dima moment does a lot more than this, also, it’s a time zone aware package, it’s one of the necessary packages in any project, in fact, the forum is using it to display the dates and times of posts, replies and comments.

@ahmadnasriya & @russian-dima instead of Moment.js, I recommend using date-fns which is almost 4 time smaller than Moment.js and is tree shakeable.

import { differenceInCalendarYears } from 'date-fns'

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    return differenceInCalendarYears(today, birthDate);
}